1. 自定义Person类,并给定一个带参构造, 当Person类的反射对象调用newInstance时会报错,写个例子演示,并说明为什么? 2. 有一个电脑类和手机类都有一个brand属性,在工厂类的静态方法中,传入反射对象及属性值,灵活获取到对应的实体对象,返回的对象中包含属性值 3、配置文件中user.properties中有一组键值对为: key=xx.xx.xx.Person 请加载配置文件后,根据key获取出value,并通过反射机制获取对应的实体对象
时间: 2024-02-06 16:08:45 浏览: 75
1. 代码示例:
```java
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) throws Exception {
Class clazz = Person.class;
Object obj = clazz.newInstance("Tom");
}
}
```
运行上述代码会抛出异常:
```
Exception in thread "main" java.lang.NoSuchMethodException: Person.<init>()
```
原因是在反射调用 `newInstance()` 方法时,会调用该类的无参构造方法来创建对象,但是 `Person` 类中只有一个带参构造方法,没有无参构造方法,所以会报错。
2. 代码示例:
```java
public class Computer {
private String brand;
public void setBrand(String brand) {
this.brand = brand;
}
@Override
public String toString() {
return "Computer{" +
"brand='" + brand + '\'' +
'}';
}
}
public class Phone {
private String brand;
public void setBrand(String brand) {
this.brand = brand;
}
@Override
public String toString() {
return "Phone{" +
"brand='" + brand + '\'' +
'}';
}
}
public class Factory {
public static Object getInstance(Class clazz, String brand) throws Exception {
Object obj = clazz.newInstance();
Field field = clazz.getDeclaredField("brand");
field.setAccessible(true);
field.set(obj, brand);
return obj;
}
}
public class Main {
public static void main(String[] args) throws Exception {
Object computer = Factory.getInstance(Computer.class, "Lenovo");
System.out.println(computer);
Object phone = Factory.getInstance(Phone.class, "Apple");
System.out.println(phone);
}
}
```
3. 代码示例:
```java
public class Person {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
public class Main {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
InputStream in = Main.class.getClassLoader().getResourceAsStream("user.properties");
props.load(in);
in.close();
String className = props.getProperty("key");
Class clazz = Class.forName(className);
Object obj = clazz.newInstance();
Method method = clazz.getDeclaredMethod("setName", String.class);
method.invoke(obj, "Tom");
System.out.println(obj);
}
}
```
假设 `user.properties` 文件中的内容如下:
```
key=com.example.Person
```
上述代码会根据 `key` 获取到 `Person` 类的类对象,并通过反射机制创建实例,并调用 `setName()` 方法设置属性值,最后输出实例对象。
阅读全文