Java定义一个方法 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-18 09:41:05 浏览: 22
好的,我会为你解答这个问题。下面是 Java 代码实现:
```java
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class ReflectionExample {
public static void main(String[] args) {
// 通过 Scanner 获取用户输入的类名和属性值
Scanner scanner = new Scanner(System.in);
System.out.println("请输入类的全名:");
String className = scanner.nextLine();
System.out.println("请输入属性值,格式为:name=value,sex=value,age=value,money=value");
String input = scanner.nextLine();
// 调用 reflectObject 方法生成对象并打印属性值
try {
Object object = reflectObject(className, input);
System.out.println(object);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException | NoSuchFieldException e) {
e.printStackTrace();
}
}
public static Object reflectObject(String className, String input) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
// 加载类
Class<?> clazz = Class.forName(className);
// 创建对象
Object object = clazz.getDeclaredConstructor().newInstance();
// 解析属性值
String[] properties = input.split(",");
for (String property : properties) {
String[] keyValue = property.split("=");
String propertyName = keyValue[0].trim();
String propertyValue = keyValue[1].trim();
// 获取属性
Field field = clazz.getDeclaredField(propertyName);
// 设置属性值
Class<?> fieldType = field.getType();
if (fieldType == String.class) {
field.set(object, propertyValue);
} else if (fieldType == int.class) {
field.setInt(object, Integer.parseInt(propertyValue));
} else if (fieldType == double.class) {
field.setDouble(object, Double.parseDouble(propertyValue));
}
}
return object;
}
}
```
你可以通过运行这个程序,输入类的全名和属性值,然后看到生成的对象并打印属性值。注意,为了让代码更加简洁,我省略了 Teacher 类的定义。