使用反射进行对象实例化
使用反射进行对象实例化,不再使用new关键字
1.第一种,使用.properties配置文件创建对象
首先需要一个实体类:
public class Phone {
String name;
int price;
@Override
public String toString() {
return "Phone{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
接下来新建一个文件夹rescources,在里面创建文件phone.properties
myphone是后面getString()方法中需要用到的key,后面是test.Phone是类的实际路径
接下来新建测试类Test
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
String name = ResourceBundle.getBundle("phone").getString("myphone");
Phone phone = (Phone) Class.forName(name).newInstance();
System.out.println(phone);
}
运行效果:
2.第二种
Class<?> phone1 = Class.forName("test.Phone");
Phone phone2 = (Phone) phone1.newInstance();
System.out.println(phone2);
3.第三种
Class<Phone> phoneClass = Phone.class;
Phone phone = phoneClass.newInstance();
System.out.println(phone);
4.获取类的所有接口名称
Class<?>[] interfaces = userClass.getInterfaces();
for (Class<?> cla:interfaces
) {
System.out.println(cla.getName());
}