package reflecttest.li;
class Test {
private String as = "It's fucking reflecting too!";
public String bs = "Reflect please!";
protected String cs = "Wait for reflecting.";
private void print(){
System.out.println("This is only a class for allowing to interview in package.");
}
protected String pef(){
return "What do you want to do?";
}
}
package reflect.li;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class OperateAnything {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, InvocationTargetException{
Class test = null;
Object obj = null;
Constructor[] constructor;
try{
test = Class.forName("reflecttest.li.Test");
constructor = test.getDeclaredConstructors();
System.out.println(constructor.length);
constructor[0].setAccessible(true);
obj = constructor[0].newInstance();
}catch (ClassNotFoundException e){
e.printStackTrace();
}
Method[] methods = test.getDeclaredMethods();
Field[] fields = test.getDeclaredFields();
for(Method m : methods){
m.setAccessible(true);
System.out.println(m.getName());
m.invoke(obj);
}
for (Field f : fields){
f.setAccessible(true);
System.out.println(f.getName() + " " + f.get(obj));
}
}
}
一般步骤:获得该类的class对象,展示它的所有构造器,在其中选择一个合适的构造器,用setAccessible方法将权限放开,然后为其创建对象,再然后就为所欲为了<( ̄︶ ̄)>。
不过访问私有内容之前,都要先将它的权限放开。