importjava.lang.reflect.Field;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;publicclassHacker{privatestaticfinalObject[]EMPTY={};publicvoidreflect()throwsIllegalAccessException,IllegalArgumentException,InvocationTargetException{Secretinstance=newSecret();Class<?>secretClass=instance.getClass();// Print all the method names & execution resultMethodmethods[]=secretClass.getDeclaredMethods();System.out.println("Access all the methods");for(Methodmethod:methods){System.out.println("Method Name: "+method.getName());System.out.println("Return type: "+method.getReturnType());method.setAccessible(true);System.out.println(method.invoke(instance,EMPTY)+"\n");}// Print all the field names & valuesFieldfields[]=secretClass.getDeclaredFields();System.out.println("Access all the fields");for(Fieldfield:fields){System.out.println("Field Name: "+field.getName());field.setAccessible(true);System.out.println(field.get(instance)+"\n");}}publicstaticvoidmain(String[]args){HackernewHacker=newHacker();try{newHacker.reflect();}catch(Exceptione){e.printStackTrace();}}}
代码清单 10.4 的控制台
Access all the methods
Method Name: getSecretCode
Return type: class java.lang.String
It's a secret
Access all the fields
Field Name: secretCode
It's a secret