java的反射java.lang.reflect包中
我们要通过反射来调用Person类的方法和属性
- public class Person{
- public void sayHello(){System.out.println('你好');}
- public String sayHello2(String name,int age){
- return name+"的年龄是"+age;
- }
- private String name;
- private int age;
- gettter(){}
- setter(){}
- }
反射方法用Method,反射属性用Field
一、反射掉调用 对象的无参无返回值的方法
- Class<?> c1 = Class.forName("com.luo.Person");//必须要知道其全路径
- // 或者通过Person类的对象p.getClass()来得到Class
- Method m1 = c1.getMethod("sayHello");
- m1.invoke(c1.newInstance());//执行方法用invoke:
二。反射调用有参有返回值的方法
- Class<?> c2 = Class.forName("com.luo.Person");
- Method m2= c2.getMethod("sayHello2",String.class,int.class);
- String s = (String)m2.invoke(c2.newInstance(),"张三",67);

















