考虑以下字节预算程序来拦截方法调用load()
:
public class ByteJavaBuddyTest {
public static class MemoryDatabase {
public List<String> load(String info) {
return Arrays.asList(info + ": foo", info + ": bar");
}
}
public static class LoggerInterceptor {
public static List<String> log(@SuperCall Callable<List<String>> zuper) throws Exception {
System.out.println("Calling database");
try {
return zuper.call();
} finally {
System.out.println("Returned from database");
}
}
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
MemoryDatabase loggingDatabase = new ByteBuddy()
.subclass(MemoryDatabase.class)
.method(named("load")).intercept(MethodDelegation.to(LoggerInterceptor.class))
.make()
.load(MemoryDatabase.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded()
.getDeclaredConstructor()
.newInstance();
System.out.println(loggingDatabase.load("qux"));
}
}
它运行并打印:
Calling database
Returned from database
[qux: foo, qux: bar]
转换为Kotlin后,它不会运行拦截器,也不会引发任何异常。
object ByteBuddyKotlinTest {
open class MemoryDatabase {
fun load(info: String): List<String> {
return Arrays.asList("$info: foo", "$info: bar")
}
}
object LoggerInterceptor {
@Throws(Exception::class)
fun log(@SuperCall zuper: Callable<List<String>>): List<String> {
println("Calling database")
try {
return zuper.call()
} finally {
println("Returned from database")
}
}
}
@Throws(
NoSuchMethodException::class,
IllegalAccessException::class,
InvocationTargetException::class,
InstantiationException::class
)
@JvmStatic
fun main(args: Array<String>) {
val loggingDatabase = ByteBuddy()
.subclass(MemoryDatabase::class.java)
.method(ElementMatchers.named("load")).intercept(MethodDelegation.to(LoggerInterceptor::class.java))
.make()
.load(MemoryDatabase::class.java.classLoader, ClassLoadingStrategy.Default.WRAPPER)
.loaded
.getDeclaredConstructor()
.newInstance()
println(loggingDatabase.load("qux"))
}
}
打印:
[qux: foo, qux: bar]
因为它不会引发任何错误,所以我真的不知道从哪里开始挖掘。
答案 0 :(得分:1)
字节好友代理通过覆盖它们的方法。如果未在Kotlin中将方法声明为open
,则在Java字节码中为final
。如果您打开方法,您的逻辑将再次起作用。