使用 byte-buddy 从字符串覆盖 class 方法?
Override a class method from a string with byte-buddy?
假设我有以下 class(或者它也可以通过接口完成吗?):
class MyCustomClass {
boolean myCustomMethod(int a, int b){}
}
以及以下字符串:
Math.abs(a - b) >= 10;
有没有办法通过 Byte Buddy,在方法 myCustomMethod 中将字符串中的代码注入到 MyCustomClass 的新子class 中?即使字符串在 ?
之前用 ANTLR 处理过
所以我得到
class MyCustomClass_SubClassInstance extends MyCustomClass {
// I know that with ByteBuddy, all this "ceremonial" code is not needed.
boolean myCustomMethod(int a, int b){
Math.abs(a - b) >= 10; // Injected code from the string
}
}
我认为你走错了路。为什么要使用 ByteBuddy 生成 class 代码?!
相反:使用 JavaCompiler 功能简单地 构建 将 class 作为 Java 源 - 然后编译它,然后使用 "dynamically"编译class.
意思是:你把事情搞得太复杂了。你实际上知道你想要得到什么 - 所以 创建 作为 java 源,并以编程方式转向 javac
将其转换为字节码。
对于 Android,JavaSourceToDex class 可能是要使用的东西。
这不是字节好友背后的想法。 Byte Buddy 做这样的事情的方法是实现一个 class 来提供你想要调用的方法,然后你生成一个代理来从检测类型委托给这个方法调用。
Javassist 提供了这样的功能,但在性能方面,在运行时编译字符串并不是很好,所以我会不惜一切代价避免这种情况。尤其是在您通常资源有限的 Android 上。 Class一代相当昂贵。
假设我有以下 class(或者它也可以通过接口完成吗?):
class MyCustomClass {
boolean myCustomMethod(int a, int b){}
}
以及以下字符串:
Math.abs(a - b) >= 10;
有没有办法通过 Byte Buddy,在方法 myCustomMethod 中将字符串中的代码注入到 MyCustomClass 的新子class 中?即使字符串在 ?
之前用 ANTLR 处理过所以我得到
class MyCustomClass_SubClassInstance extends MyCustomClass {
// I know that with ByteBuddy, all this "ceremonial" code is not needed.
boolean myCustomMethod(int a, int b){
Math.abs(a - b) >= 10; // Injected code from the string
}
}
我认为你走错了路。为什么要使用 ByteBuddy 生成 class 代码?!
相反:使用 JavaCompiler 功能简单地 构建 将 class 作为 Java 源 - 然后编译它,然后使用 "dynamically"编译class.
意思是:你把事情搞得太复杂了。你实际上知道你想要得到什么 - 所以 创建 作为 java 源,并以编程方式转向 javac
将其转换为字节码。
对于 Android,JavaSourceToDex class 可能是要使用的东西。
这不是字节好友背后的想法。 Byte Buddy 做这样的事情的方法是实现一个 class 来提供你想要调用的方法,然后你生成一个代理来从检测类型委托给这个方法调用。
Javassist 提供了这样的功能,但在性能方面,在运行时编译字符串并不是很好,所以我会不惜一切代价避免这种情况。尤其是在您通常资源有限的 Android 上。 Class一代相当昂贵。