java反射与获取方法相关的代码练习
package com.hpe.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.junit.Test;
public class TestMethod {
@Test
public void test1() {
Class clazz = Person.class;
Method[] ms = clazz.getMethods();
for (Method m : ms) {
System.out.println(m);
}
System.out.println("-----------------------");
Method[] ms1 = clazz.getDeclaredMethods();
for (Method m : ms1) {
System.out.println(m);
}
}
@Test
public void test2() throws Exception {
Class<Person> clazz = Person.class;
Person p = (Person)clazz.newInstance();
Field f_name = clazz.getField("name");
f_name.set(p, "jack");
Field f_age = clazz.getDeclaredField("age");
f_age.setAccessible(true);
f_age.set(p, 20);
Method m1 = clazz.getMethod("show");
m1.invoke(p);
Method m2 = clazz.getMethod("toString");
Object returnV2 = m2.invoke(p);
System.out.println(returnV2);
Method m3 = clazz.getMethod("info");
m3.invoke(Person.class);
Method m4 = clazz.getDeclaredMethod("display", String.class);
m4.invoke(p, "China");
}
@Test
public void test3() throws Exception {
Class<Person> clazz = Person.class;
Constructor<Person> con = clazz.getConstructor(String.class,int.class);
Person p = con.newInstance("rose",18);
Method m1 = clazz.getMethod("display", String.class);
m1.invoke(p, "Japan");
}
}