代码如下:
- package myfirstdemo;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- public class reflect_demo3
- {
-
- public static void main(String[] args) throws Exception
- {
- // TODO Auto-generated method stub
- Class<human> per=(Class<human>) Class.forName("myfirstdemo.human");//获取class对象
- Constructor<human> cr=per.getConstructor(int.class,String.class);//此处提示 java.lang.NoSuchMethodException 异常 这里不明白????
-
- human hu=(human)cr.newInstance(20,"man");
- hu.run();
-
- Field f=per.getDeclaredField("sex");//获取私有变量
- f.setAccessible(true);//暴力反射
- f.set(hu,"women");
-
-
- Method run=per.getMethod("run",null);
- run.invoke(hu,null);
- }
- }
- class human //
- {
- private int age=0;
- private String sex=null;
- human(int age,String sex)//带参数构造方法
- {
- this.age=age;
- this.sex=sex;
- }
- public void run(){
- System.out.println(age+sex);
- }
-
-
- }
复制代码 |