ich habe eine klasse mit einer funktion die nicht public ist. und versuche diese per reflection aufzurufen.
Java:
publicclassSecretClass{privateint visibleIndex =0;voidsetVisibleIndex(int newVisibleIndex){System.out.println("setting visible index to "+newVisibleIndex);this.visibleIndex = newVisibleIndex;}intgetVisibleIndex(){return visibleIndex;}}
und die klasse dazu, die per reflection darauf zugreifen soll:
Java:
importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;publicclassHacking{/**
* this function hacks up secret code ;o)
*/publicstaticvoidsecretClass(){Class<?> secretClass =SecretClass.class;Object instance =newSecretClass();Method[] methods = secretClass.getDeclaredMethods();System.out.println("declared functions in class "+ secretClass.getSimpleName());for(int i =0; i < methods.length; i++){try{System.out.println(String.format("%s %s(%s);",
methods[i].getReturnType(), methods[i].getName(),
methods[i].getParameterTypes()[0]));}catch(Exception e){System.out.println(String.format("%s %s();",
methods[i].getReturnType(), methods[i].getName()));}}Method method;try{
method = secretClass.getMethod("setVisibleIndex",int.class);
method.setAccessible(true);System.out.println(method.invoke(instance,12)+"\n");}catch(SecurityException e){
e.printStackTrace();}catch(IllegalArgumentException e){
e.printStackTrace();}catch(IllegalAccessException e){
e.printStackTrace();}catch(InvocationTargetException e){
e.printStackTrace();}catch(NoSuchMethodException e){
e.printStackTrace();}}publicstaticvoidmain(String[] args){Hacking.secretClass();}}
ich wäre froh, wenn mir jemand sagen könnte, was ich falsch mache...
denn die funktion gibts definitiv und dennoch bekomme ich eine NoSuchMethodException?!
soll jetzt jemand anders auch nachschlagen?
es wäre doch angenehm hilfreich von dir, in diesem Zweifelsfall die beiden Methoden-Beschreibungen hier zu zitieren
ansonsten kannst du auch alle Konstellationen testen, neben public oder nicht spielt vielleicht auch Vererbung eine Rolle,
Methode selber definiert oder nur geerbt?
Method getMethod(String name, Class... parameterTypes)
Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.
Method[] getMethods()
Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
[..] all the methods declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private methods, but excludes inherited methods.