Skip to content

Instantly share code, notes, and snippets.

@takawitter
Last active December 19, 2015 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takawitter/5993155 to your computer and use it in GitHub Desktop.
Save takawitter/5993155 to your computer and use it in GitHub Desktop.
https://gist.github.com/takawitter/5993052 の続き。こんな感じでメソッドを検索して、安全に実行できるものを見つけてやる。実際のケースではパラメータのマッチングが加わるから、より複雑なコードになるけど。あと、最初に見つかった(呼ぶとIllegalAccessExceptionになる)メソッドでも、setAccessible(true)してやるとたいてい呼べる。但し呼べるかどうかはSecurityManager次第なので、この方法の方が安全。
import java.lang.reflect.Method;
public class InvokeSafely{
public static Object invokeSafely(Object obj, String method) throws Throwable{
Class<?> c = obj.getClass();
Method m = c.getMethod(method);
try{
return m.invoke(obj);
} catch(IllegalAccessException e){
}
while(c != null){
for(Class<?> i : c.getInterfaces()){
try{
return i.getMethod(method).invoke(obj);
} catch(NoSuchMethodException e){
}
}
c = c.getSuperclass();
}
throw new NoSuchMethodException(method);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment