我有一個接口的名稱,我想調用由其具體實現的類定義的方法。所以我接受了Java Reflection的幫助。Java反射:從接口名稱調用方法
接口:
package tsb.learning.reflection;
public interface IAnyThing {
void doSomething();
}
它的實現類:
package tsb.learning.reflection;
public class AnyThing implements IAnyThing {
public void doSomething() {
System.out.println("JYM");
}
}
的InvocationHandler
實施:
package tsb.learning.reflection;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class AnyInvocationHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(proxy, args);
}
}
和控制器:
package tsb.learning.reflection;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Controller {
/**
* @param args
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException {
String interfaceName = "tsb.learning.reflection.IAnyThing";
ClassLoader classLoader = Class.forName(interfaceName).getClassLoader();
Class<?>[] interfaces = new Class<?>[] { Class.forName(interfaceName) };
InvocationHandler handler = new AnyInvocationHandler();
IAnyThing anyThing = (IAnyThing) Proxy.newProxyInstance(classLoader, interfaces, handler);
anyThing.doSomething();
}
}
但它不工作,我得到以下異常:
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at tsb.learning.reflection.AnyInvocationHandler.invoke(AnyInvocationHandler.java:10)
at $Proxy0.doSomething(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at tsb.learning.reflection.AnyInvocationHandler.invoke(AnyInvocationHandler.java:10)
at $Proxy0.doSomething(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at tsb.learning.reflection.AnyInvocationHandler.invoke(AnyInvocationHandler.java:10)
at $Proxy0.doSomething(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at tsb.learning.reflection.AnyInvocationHandler.invoke(AnyInvocationHandler.java:10)
唯一的例外是在控制檯打印的循環,我需要停止該程序。
任何信息對我都很有幫助。
謝謝。所以方法'AnyInvocationHandler#invoke'的實現可以嗎? –
@TapasBose我重寫的方式是,是的。 ;) –
感謝您的代碼片段正在工作。但是如果我不知道實施課程,在這裏AnyThing,那我該怎麼做?其實它是一個演示應用程序。實際上我不知道哪個類實現了它。 –