gpt4 book ai didi

java - ByteBuddy - 无法拦截来自父类(super class)的静态方法

转载 作者:行者123 更新时间:2023-12-05 06:17:36 29 4
gpt4 key购买 nike

我正在为 Android 开发命令行工具(想想我),试图利用 ByteBuddy 的强大功能来 stub android.security.KeyStore 中定义的静态方法 getApplicationContext

但是 - 在对 android.security.KeyStore 进行子类化时,该方法似乎对 ByteBuddy getDeclaredMethods 不可见,因此无法拦截它。

当从反射 API 使用 getMethods 时,我能够列出方法。

            Class AndroidKeyStore = Class.forName("android.security.KeyStore");
Method[] keyStoreMethods = new ByteBuddy()
.with(TypeValidation.DISABLED)
.subclass(AndroidKeyStore, ConstructorStrategy.Default.IMITATE_SUPER_CLASS)
.name("KeyStoreMasker")
.method(ElementMatchers.named("getApplicationContext"))
.intercept(SuperMethodCall.INSTANCE)
.make()
.load(getClass().getClassLoader(),
new AndroidClassLoadingStrategy
.Injecting(new File("/data/app/cmdutil")))
.getLoaded()
.getDeclaredMethods();
for(i = 0; i < keyStoreMethods .length; i++) {
System.out.println("method = " + keyStoreMethods[i].toString());
}

运行上面的代码时,我希望子类中只有一个方法 - getApplicationContext。但是子类不包含任何方法。

将对 getDeclaredMethods 的调用替换为 getMethods 我能够列出父类(super class)的所有公共(public)方法。

通过将截获的方法替换为非静态方法(例如“state”),我能够使用 ByteBuddy 的 getDeclaredMethods 函数列出该方法:

Number of declared methods in keyStoreMethods: 2

method = public android.security.KeyStore$State AndroidKeyStoreMasker.state()

method = public android.security.KeyStore$State AndroidKeyStoreMasker.state(int)

所以我的最终结论是 ByteBuddy(或我在 ByteBuddy 的使用案例)在静态方法可见性方面存在一些问题。

引用android.security.KeyStore.java: https://android.googlesource.com/platform/frameworks/base/+/master/keystore/java/android/security/KeyStore.java

如有任何帮助,我们将不胜感激。

最佳答案

在创建子类时,字节好友只能拦截子类直接声明的方法或父类(super class)的虚方法。这就是 JVM 的工作方式,static 方法直接在接收器上分派(dispatch)。

Byte Buddy 也能够重新定义和重新转换现有的类,但这需要 Java 代理,而这在 Android 上不可用。因此,恐怕你需要找到一个非静态 Hook 点来完成你正在尝试的事情。或者,查看 MemberSubstitution,您可以在其中重定向代码中的此类调用。这也需要重新转换,但由于它发生在您的代码中,您可以使用 Byte Buddy 的构建插件。

关于java - ByteBuddy - 无法拦截来自父类(super class)的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61572835/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com