使用构造方法创建对象(不管是有参数还是无参数的构造方法)的方式并不灵活
使用反射机制创建对象就非常灵活:
public class Main5
{
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, IOException
{
Constructor<File> constructor= File.class.getDeclaredConstructor(String.class);
//注意这里不使用File file=new File();的方式创建一个File类对象,而是采取下面反射的方式创建
File file= constructor.newInstance("D://testouyangshuiming.txt");
file.createNewFile();
//输出文件是否被创建好了
System.out.println(file.exists());//true
}
}