Java反射API的应用示例:创建动态类与方法
Java的反射API允许我们在运行时获取类的信息,包括构造函数、方法和属性等。下面是一个简单的应用示例:
- 创建一个动态类(使用
Class<YourClassName>
创建):
// 假设我们要创建一个名为Person的类
String className = "Person"; // YourClassName
// 使用反射API创建类
Class<Person> personClass = Class.forName(className);
- 创建对象并调用方法:
// 获取Person类的一个对象
try {
Person person = personClass.newInstance(); // create object
} catch (Exception e) {
System.err.println("Error creating instance: " + e.getMessage());
return;
}
// 调用方法:假设我们有一个名为sayHello的方法
Method method = personClass.getMethod("sayHello",()); // get method
// 调用方法并打印结果
Object result = method.invoke(person, new Object[]{})); // call method
if (result instanceof String) {
System.out.println((String) result); // print result if string
} else {
System.out.println("Method result is not a string: " + result)); // print if not string
}
这个示例创建了一个名为Person的动态类,然后创建了该类的一个对象,并调用了名为sayHello的方法。
还没有评论,来说两句吧...