不多说,先上实例
- /**
- * 描述人的类
- * @author Administrator
- *
- */
- public class Person{
- private String name;//姓名
- private int age;//年龄
- public Person(){}
- public Person(String name,Integer age){//带参的构造函数
- this.name=name;
- this.age=age;
- }
-
- /**
- * 获得姓名
- * @return
- */
- public String getName() {
- return name;
- }
- /**
- * 修改姓名
- * @param name
- */
- public void setName(String name) {
- //System.out.println("setName");
- this.name = name;
- }
- /**
- * 获得年龄
- * @return
- */
- public int getAge() {
- return age;
- }
- /**
- * 修改年龄
- * @param age
- */
- public void setAge(int age) {
- this.age = age;
- }
-
- }
复制代码
- public class Test {
- public static void main(String[] args) {
- //获得该类的字节码文件对象
- try {
- Class clazz=Class.forName("com.itheimas.Person");
- //获得对象的构造器
- Constructor constructor=clazz.getConstructor(String.class,Integer.class);
- //通过构造器创建实例
- Object obj=constructor.newInstance("张三",23);
- //Object obj=clazz.newInstance();
- //使用反射方式调用setName方法对名称进行设置
- Method method=clazz.getMethod("setName",String.class);
- //反射的方法调用
- method.invoke(obj,"李四");
-
- //不使用setAge方法直接使用反射方式对age赋值
- Field field=clazz.getDeclaredField("age");//获得年龄属性,并包装成发射对象
- field.setAccessible(true);//暴力访问
- field.set(obj,30);
- System.out.println(field.get(obj));
-
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- System.out.println("没有发现该类");
- } catch (SecurityException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (NoSuchMethodException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InstantiationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (NoSuchFieldException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
复制代码
问题是:在Person类中,有参构造器参数里面必须定义引用类型变量才能在反射中找到这个构造函数么? |
|