欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > 安卓model转鸿蒙ets

安卓model转鸿蒙ets

2024/10/25 1:34:17 来源:https://blog.csdn.net/luozhi3527/article/details/141868456  浏览:    关键词:安卓model转鸿蒙ets

现在的android studio提供了java自动转kotlin的实现,非常方便。

那android的java和kotlin有没有可能转成鸿蒙arkts呢。

本质上都是字符串文件,讲道理应该是可行的。

先从最简单的model转换开始,把kotlin的model转成ets。

通过插件的形式把kt/java文件转成ets文件,贴个kt2ets的方法:

fun convertKt2Ets(ktCode: String): String {val lines = ktCode.split("\n")var inClass = falsevar hasBigQuo = falsevar dataClassName = ""val tsLines = mutableListOf<String>()for (line in lines) {when {// classline.startsWith("class ") -> {// class contentinClass = true// 是个data classif (line.contains("{")) {hasBigQuo = true}dataClassName = line.substringAfter("class").substringBefore("(")if (dataClassName != null) {tsLines.add("export interface ${dataClassName.trim()} {")}}// fieldsinClass && (line.contains("val") || line.contains("var")) -> {val fields = line.split(",")fields.forEach { field ->val pureCode = field.replace("val", "").replace("var", "")val parts = pureCode.split(":")if (parts.size == 2) {val name = parts[0].trim()val hasQue = parts[1].contains("?")val useQue = if (hasQue) {"?"} else {""}var type = convertKtType2EtsType(parts[1].replace("?", "").trim())// 数组变量if (type.contains("List<") || type.contains("ArrayList<")) {type = type.replace("List<", "").replace("ArrayList<", "").replace(">", "")type = "${type}[]"}tsLines.add("    $name${useQue}: $type")} else {println("not format field line")}}}// fun 2 functionline.contains("fun ") -> {val functionName = line.substringAfter("fun ").substringBefore("(")val params = line.substringAfter("(").substringBefore(")").split(",").joinToString(", ") {val (paramName, paramType) = it.trim().split(":")"${paramName.trim()}: ${convertKtType2EtsType(paramType.trim())}"}val returnType = convertKtType2EtsType(line.substringAfter("):").substringBefore("{").trim())tsLines.add("function $functionName($params): $returnType {")}(inClass && line.contains("}")) -> {tsLines.add(line)inClass = falsehasBigQuo = false}(inClass && !hasBigQuo && line.contains(")")) -> {tsLines.add("}")inClass = falsehasBigQuo = false}(line.startsWith("package") || line.startsWith("import ")) -> {// remove line}else -> {tsLines.add(line)}}}return tsLines.joinToString("\n")}private fun convertKtType2EtsType(type: String): String {return type.replace("String", "string").replace("Int", "number").replace("Float", "number").replace("Double", "number").replace("Boolean", "boolean").replace("Long", "number")}

后续公布源码

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com