各自努力,最高处见!加油!
一、练习一
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Homework01 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
Class<?> privateTestClass = Class.forName("Homework.PrivateTest");
Constructor<?> declaredConstructor = privateTestClass.getDeclaredConstructor();
Object o = declaredConstructor.newInstance();//创建一个对象
Field name = privateTestClass.getDeclaredField("name");
name.setAccessible(true);
name.set(o,"xmt");
Method getName = privateTestClass.getDeclaredMethod("getName");
Object invoke = getName.invoke(o);
System.out.println(invoke);
}
}
public class PrivateTest {
private String name="hellokitty";
public String getName(){
return name;
}
}
二、练习二
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Homework02 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> fileClass = Class.forName("java.io.File");
Constructor<?>[] constructors = fileClass.getConstructors();
for (Constructor<?> constructor : constructors) {
System.out.println("File构造器"+constructor.getName());
}
Constructor<?> fileClassConstructor = fileClass.getConstructor(String.class);
Object o = fileClassConstructor.newInstance("D:\\Java_code\\reflection\\src\\myNew.txt");
Method createNewFile = fileClass.getDeclaredMethod("createNewFile");
createNewFile.invoke(o);
}
}