gpt4 book ai didi

java-反射: How to Override private static abstract inner class method?

转载 作者:行者123 更新时间:2023-12-01 04:50:35 25 4
gpt4 key购买 nike

我有以下类(class):

class MyClass{

private static final int VERSION_VALUE = 8;

private static final String VERSION_KEY = "versionName";

public boolean myPublicMethod(String str) {
try {
return myPrivateMethod(str, VERSION_KEY, VERSION_VALUE,
new MyInnerClass() {

@Override
public InputStream loadResource(String name) {
//do something important
}
});
}
catch (Exception e) {
}
return false;
}


private boolean myPrivateMethod(String str, String key, int version,
ResourceLoader resourceLoader) throws Exception
{
//do something
}

private static abstract class MyInnerClass {

public abstract InputStream loadResource(String name);

}
}

我想为 myPrivateMethod 编写单元测试,我需要为其传递 resourceLoader 对象并覆盖它的 loadResource 方法。

这是我的测试方法:

@Test
public void testMyPrivateMethod() throws Exception {
Class<?> cls = Class.forName("my.pack.MyClass$MyInnerClass");
Method method = cls.getDeclaredMethod("loadResource", String.class);
//create inner class instance and override method
Whitebox.invokeMethod(myClassObject, "testValue1", "testValue2", "name1", 10, innerClassObject);
}

请注意,我无法更改代码。

最佳答案

嗯,你可以使用Javassist ...

参见this question 。我还没有尝试过这个,但是当你想要覆盖时你可以调用这个方法:

public <T extends Object> T getOverride(Class<T> cls, MethodHandler handler) {
ProxyFactory factory = new ProxyFactory();
factory.setSuperclass(cls);
factory.setFilter(
new MethodFilter() {
@Override
public boolean isHandled(Method method) {
return Modifier.isAbstract(method.getModifiers());
}
}
);

return (T) factory.create(new Class<?>[0], new Object[0], handler);
}

关于java-反射: How to Override private static abstract inner class method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15054085/

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