通过反射创建新的文件
package com.zqf.fanshe.Class_;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class reflection08 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> fileClass = Class.forName("java.io.File");
Constructor<?> declaredConstructor1 = fileClass.getDeclaredConstructor(String.class);
String filepath="C:\\idea\\xiangmu\\newnew.txt";
Object file = declaredConstructor1.newInstance(filepath);//创建File对象
//得到方法对象
Method createNewFile = fileClass.getMethod("createNewFile");
createNewFile.invoke(file);
System.out.println(filepath.getClass());
System.out.println("创建文件成功"+filepath);
}
}
通过反射修改私有属性的值 并且调用公有方法
package com.zqf.fanshe.Class_;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class reflection07 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException {
//得到Test对象的Class对象
Class<?> testClass = Class.forName("com.zqf.fanshe.Class_.Test");
//创建对象实例
Object o = testClass.newInstance();
//得到属性值
Field field = testClass.getDeclaredField("name");
field.setAccessible(true);
field.set(o,"hello jack");
//得到公有方法getname
Method method = testClass.getMethod("getName");
Object invoke = method.invoke(o);
System.out.println("name属性的值"+invoke);
}
}
class Test{
private String name="hellokitty";
public String getName() {
return name;
}
}