上一篇经过Class能够获取一个类的类模板了而且能够经过类模板成功的创造出了对象,可是止步于此是没有意义的由于单纯的拿到对象而不去作具体的事对一个对象来讲它是很伤心的,下面就看看怎么能取得method来让咱们的对象作具体的事。
java
写一个student类,它有两个方法 一个是say()方法 一个是run方法spa
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中方法的模板
code
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 get
declare methods:hash
run say it
从输出结果上能够看出clazz.getMethods()这个方法他获取的是该类的全部方法包含了从父类继承的方法,而clazz.getDeclaredMethods()这个方法只获取它本身的方法而不包含从父类继承的方法io
那么咱们如今获取到了类的方法的模板,那么怎么才能执行该类的方法呢?模板
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方法,固然还须要传递两个参数,第一个参数说明你须要执行的是那个对象中的方法,第二个参数是为你要执行的方法传递对应的参数。