上一篇通过Class可以获取一个类的类模板了并且可以通过类模板成功的创造出了对象,但是止步于此是没有意义的因为单纯的拿到对象而不去做具体的事对一个对象来说它是很伤心的,下面就看看怎么能取得method来让我们的对象做具体的事。
写一个student类,它有两个方法 一个是say()方法 一个是run方法
public class Student {
public String say(String words){
System.out.println("这位同学说了:"+words);
return words;
}
public void run(int distance){
System.out.println("这位同学跑了:"+distance+"km");
}
}
我们可以通过Method这个类来获取Student中方法的模板
public class Test {
public static void main(String[] args) {
try {
Class clazz=Class.forName("com.tl.referce.Student");
System.out.println("method:");
Method methods1[]=clazz.getMethods();
for (Method method : methods1) {
System.out.print(method.getName()+"\t");
}
System.out.println();
System.out.println("declare methods:");
Method methods2[]=clazz.getDeclaredMethods();
for (Method method : methods2) {
System.out.print(method.getName()+"\t");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
输出结果是:
method:
run say wait wait wait equals toString hashCode getClass notify notifyAll
declare methods:
run say
从输出结果上可以看出clazz.getMethods()这个方法他获取的是该类的所有方法包含了从父类继承的方法,而clazz.getDeclaredMethods()这个方法只获取它自己的方法而不包含从父类继承的方法
那么我们现在获取到了类的方法的模板,那么怎么才能执行该类的方法呢?
public class Test {
public static void main(String[] args) {
try {
Class clazz=Class.forName("com.tl.referce.Student");
Method methods1[]=clazz.getMethods();
System.out.println();
Method methods2[]=clazz.getDeclaredMethods();
try {
Student student1=(Student) clazz.newInstance();
Method method=clazz.getDeclaredMethod("say", new Class[]{String.class});
method.invoke(student1, "hello world");
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
我们通过 Method method=clazz.getDeclaredMethod("say", new Class[]{String.class});来获取clazz中一个名叫say的方法的method模板然后通过method的invoke方法来执行student的say方法,当然还需要传递两个参数,第一个参数说明你需要执行的是那个对象中的方法,第二个参数是为你要执行的方法传递对应的参数。