import lombok.Data;
import java.util.Arrays;
/**
* @author admin
*/
@Data
public class MyPeople {
private int age;
private String name;
public void eat1(String ... footNames){
System.out.print("name[" + this.name + "],age[" + this.age + "],");
System.out.print("eat footName is");
if(footNames != null){
Arrays.asList(footNames).forEach(footName -> System.out.print(footName + ","));
}
}
public void eat2(int footNum,String ... footNames){
System.out.print("name[" + this.name + "],age[" + this.age + "],");
System.out.print("eat " + footNum + " foot,footName is");
System.out.print("eat footName ");
if(footNames != null){
Arrays.asList(footNames).forEach(footName -> System.out.print(footName + ","));
}
}
}
参数说明
name指的是方法名称
java.lang.Class<T> @Contract(pure = true)
@NotNull
public reflect.Method getMethod(@NonNls @NotNull String name,
Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException
obj指的是类的实例,可以为null
java.lang.reflect.Method public Object invoke(Object obj,
Object... args)
throws IllegalAccessException, IllegalArgumentException, reflect.InvocationTargetException
import java.lang.reflect.Method;
public class ReflectTest {
public static void main(String[] args) {
MyPeople myPeople = new MyPeople();
myPeople.setAge(12);
myPeople.setName("gaoshan");
Class<MyPeople> myPeopleClass = MyPeople.class;
try {
Method eatMethod1 = myPeopleClass.getMethod("eat1",String[].class);
eatMethod1.invoke(myPeople,new Object[]{new String[]{"aa","bb","cc"}});
System.out.println();
Method eatMethod2 = myPeopleClass.getMethod("eat2",int.class,String[].class);
eatMethod2.invoke(myPeople,100,new String[]{"aa","bb","cc"});
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行结果
name[gaoshan],age[12],eat footName isaa,bb,cc,
name[gaoshan],age[12],eat 100 foot,footName iseat footName aa,bb,cc,