实习期间遇到一个题,题目大致是从一个文件中读取内容,文件格式如下:类名:属性名=值,属性名=值……。有若干行这样的数据,要求根据文件内容实例化类并且为其属性赋值,最后调用该类方法,输出类的各属性。
之前一直不会如何讲给定的类实例化,学习后代码如下:
package com.qunar.fresh.wangchaowang.exam1.test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by wangchao on 15-3-13.
*/
public class Test {
public static void main(String[] args) {
try {
// 根据给定的类名初始化类
Class catClass = Class.forName("com.qunar.fresh.wangchaowang.exam1.test.Cat");
// 实例化这个类
Object obj = catClass.newInstance();
// 获得这个类的所有方法
Method[] methods = catClass.getMethods();
// 循环查找想要的方法
for(Method method : methods) {
if("setName".equals(method.getName())) {
// 调用这个方法,invoke第一个参数是类名,后面是方法需要的参数
method.invoke(obj, "Tom" );
}
}
// 调用指定方法
catClass.getMethod("shout").invoke(obj, null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
class Cat {
private String name;
public void setName(String name) {
this.name = name;
}
public void shout() {
System.out.println("My name is " + this.name + "!");
}
}