参考书籍java程序员修炼之道 发射的例子 package thread; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Teacher { public String getName(String name, String address, Integer age
参考书籍<<java程序员修炼之道>>
发射的例子
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Teacher {
public String getName(String name, String address, Integer age) {
return name + "是一名人民教师,在"+address+","+age+"岁";
}
public static void main(String[] args) {
try {
Class<?> clazz = Class.forName("thread.Teacher");
Method method = clazz.getMethod("getName", String.class, String.class, Integer.class);
Object obj = method.invoke(clazz.newInstance(), "李梅","上海", 21);
System.out.println(obj);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
java7句柄的例子:
public class Student {private String name;
public Student() {
}
public Student(String name) {
this.name = name;
}
public void say() {
System.out.println(this.name + "我想去厕所");
}
public static void main(String[] args) {
Class<?> aClass = MethodHandles.lookup().lookupClass();
System.out.println(aClass);
// test();
}
private static void test() {
MethodType methodType = MethodType.methodType(Void.TYPE);
Student student = new Student("小米");
try {
MethodHandle say = MethodHandles.lookup().findVirtual(Student.class, "say", methodType);
say.invokeExact(student);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}