package reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
try {
Class c = Class.forName("reflect.Student");// 根据类的完整类名创建类象
Object obj = (Student) c.newInstance();// 实例化类,强至类型转换
System.out.println(obj);
Method met = c.getMethod("sayHi", new Class[] { String.class });// 得到名字为sayHi的方法
String say = (String) met.invoke(obj, new Object[] { "ss" });//调用方法得到返回值
System.out.println(say);
} catch (ClassNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (InstantiationException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (SecurityException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
}
class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String sayHi(String hobby) {
age = 18;
name = "丰丰";
String say = "大家好,我叫" + name + "我今年" + age + "岁" + hobby;
return say;
}
}