3
リフレクションを使用して、特定のアノテーションでアノテーションされたクラスからメソッドを取得しています。クラスのメソッドのリストを取得すると、メソッドをループし、メソッドが特定の戻り値の型と一致する場合、そのメソッドを呼び出したいと思います。テスト目的のために、私が得ているメソッドがStringを返すことを知っています。リフレクションを使用してメソッドを呼び出すときに渡すオブジェクト
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setScanners(new TypesScanner(), new TypeElementsScanner())
.setUrls(ClasspathHelper.forPackage("stressball"))
);
Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(DependantClass.class);
System.out.println(annotated);
for(Class<?> clazz : annotated) {
for(Method method : clazz.getMethods()) {
if(method.isAnnotationPresent(DependantResource.class)) {
if(method.getReturnType() == String.class) {
System.out.println(method.invoke(method,(Object[]) null));
}
}
}
}
これは私が
@DependantResource
public String showInjector() {
return "This is an injector";
}
を起動しようとしています方法である私は、次のエラーを取得しておくと、私はそれは私が呼び出しに渡していたオブジェクトに関係するすべてのものを持って知っているが、方法であり、ループから、私は通過するはずの物体ではない?
Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at stressball.test.DefaultTest.main(DefaultTest.java:35)
私はそれが何か簡単なことを知っていた...ありがとう。 – ryandlf