reflectObject(String package_class_name,String input) 该方法用于生成package_class_name所对应的类的实例对象,并初始化对象中的属性值。 举例: 入参:com.gec.Person, name=admin,sex=男,age=38,则生成一个Person对象,并给该对象赋值admin,男,38 要求: --现有Teacher类【String name、String sex、int age、int level】 --现有Person类【String name、String sex、int age、double money】 --通过Scanner分别输入类的全名和input字符串,然后调用reflectObject方法,生成对象并打印
时间: 2024-03-17 08:47:47 浏览: 148
好的,以下是代码实现:
```
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入类的全名:");
String className = scanner.nextLine();
System.out.println("请输入属性值:");
String input = scanner.nextLine();
try {
Object object = reflectObject(className, input);
System.out.println(object);
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
}
public static Object reflectObject(String packageClassName, String input) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class<?> clazz = Class.forName(packageClassName);
Object obj = clazz.getConstructor().newInstance();
String[] params = input.split(",");
for (String param : params) {
String[] keyValue = param.split("=");
String fieldName = keyValue[0].trim();
String fieldValue = keyValue[1].trim();
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
String fieldType = field.getType().getName();
if (fieldType.equals("java.lang.String")) {
field.set(obj, fieldValue);
} else if (fieldType.equals("int")) {
field.setInt(obj, Integer.parseInt(fieldValue));
} else if (fieldType.equals("double")) {
field.setDouble(obj, Double.parseDouble(fieldValue));
}
}
return obj;
}
}
class Teacher {
private String name;
private String sex;
private int age;
private int level;
public Teacher() {
}
public Teacher(String name, String sex, int age, int level) {
this.name = name;
this.sex = sex;
this.age = age;
this.level = level;
}
@Override
public String toString() {
return "Teacher{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", level=" + level +
'}';
}
}
class Person {
private String name;
private String sex;
private int age;
private double money;
public Person() {
}
public Person(String name, String sex, int age, double money) {
this.name = name;
this.sex = sex;
this.age = age;
this.money = money;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", money=" + money +
'}';
}
}
```
运行代码,输入类的全名 com.gec.Teacher,输入属性值 name=Tom,sex=男,age=30,level=5,输出结果为:
```
Teacher{name='Tom', sex='男', age=30, level=5}
```
再次运行代码,输入类的全名 com.gec.Person,输入属性值 name=Lucy,sex=女,age=25,money=5000.0,输出结果为:
```
Person{name='Lucy', sex='女', age=25, money=5000.0}
```
阅读全文