小编赵小鱼*_*赵小鱼的帖子

如何通过java反射获取kotlin扩展中声明的Properties或Function

如果我像这样在 Kotlin 中声明一个扩展函数或一些扩展属性

var View.newPosition: Int
    get():Int {
        return newPosition
    }
    set(value) {
        this.newPosition=value
        Log.e("test","newPosition"+newPosition)
    }


fun View.setPosition(value:Int ){
    Log.e("test", "Position" + value)
}
Run Code Online (Sandbox Code Playgroud)

然后我想通过Java反射来获取它们,如下所示

    Class stuClass = null;
    try {
        stuClass = Class.forName("android.view.View");
    } catch (Exception e) {
        Log.e("test", e.toString());
    }
    Field f = null;
    try {
        f = stuClass.getField("newPosition");
    } catch (Exception e) {
        Log.e("test", e.toString());
    }
    Object obj = null;
    try {
        obj = stuClass.getConstructor().newInstance();
    } catch (Exception e) {
        Log.e("test", e.toString());
    }

    try {
        f.set(obj, 555); …
Run Code Online (Sandbox Code Playgroud)

java kotlin

6
推荐指数
1
解决办法
1785
查看次数

标签 统计

java ×1

kotlin ×1