<pre name="code" class="java"><pre name="code" class="java">package com.mypractice.second;
public class MethodDemo {
private String name;
private int age;
public void getInfo(){ //无参方法
name = "朱天鹏1";
age = 21;
}
public void getInfo(String name){ //一个参数方法
this.name = name;
age = 22;
}
public void getInfo(String name,int age){ //两个参数方法
this.name = name;
this.age = age;
}
public void getMessage(){ //获取信息
System.out.println("name:"+name+"\nage:"+age);
}
}
package com.mypractice.second;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MethodDemoTest {
/**
* @param args
* @throws IllegalAccessException
* @throws InstantiationException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
//使用无参方法
Class c = MethodDemo.class; //获取Class类
MethodDemo methodDemo1 = (MethodDemo)c.newInstance(); //反射MethodDemo对象
Method method1 = c.getMethod("getInfo", null); //获取getInfo()方法
method1.invoke(methodDemo1, null); //调用获取的方法
methodDemo1.getMessage(); //打印方法的信息
//使用有参方法
MethodDemo methodDemo2 = (MethodDemo)c.newInstance(); //反射MethodDemo对象
Method method2 = c.getMethod("getInfo",String.class,int.class);
method2.invoke(methodDemo2,"aaa",22);
methodDemo2.getMessage();
}
}
运行结果:
总结:
1.调用方法时
<pre name="code" class="java"> Method method2 = c.getMethod("getInfo",String.class,int.class);
必须使用int.class 不能使用Integer.class。而构造方法中则使用Integer.class
2.invoke(obj,objs...),第一个参数为你要使用方法的对象,第二个参数是可变参数,为你要传入的参数。