Java反射机制

1、不通过new一个对象,还可以怎么创建对象?

  通过java反射机制创建对象

2、private的属性绝对安全吗?

  不安全,可以通过反射机制对私有属性进行赋值

3、反射应用场景:jdbc驱动加载、SpringIOC

4、创建UserTest类

package com.cppdy;

public class UserTest {

    private String name;
    private String sex;

    public UserTest() {

    }

    public UserTest(String name, String sex) {
        this.name = name;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "User [name=" + name + ", sex=" + sex + "]";
    }

}

4、创建IOCTest类(反射案例)

package com.cppdy;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class IOCTest {

    public static void main(String[] args) throws Exception {
        Class<?> forName = Class.forName("com.cppdy.UserTest");
        //通过无参构造函数创建实例
        UserTest user1 = (UserTest) forName.newInstance();
        System.out.println(user1.toString());
        //通过有参构造函数创建实例
        Constructor<?> constructor = forName.getConstructor(String.class,String.class);
        UserTest user2 = (UserTest)constructor.newInstance("吹泡泡的魚","男");
        System.out.println(user2.toString());
        //通过反射机制对私有属性进行赋值
        Object newInstance = forName.newInstance();
        Field declaredField1 = forName.getDeclaredField("name");
        Field declaredField2 = forName.getDeclaredField("sex");
        //设置允许访问私有成员
        declaredField1.setAccessible(true);
        declaredField2.setAccessible(true);
        
        declaredField1.set(newInstance, "cppdy");
        declaredField2.set(newInstance, "nan");
        
        UserTest user3 = (UserTest)newInstance;
        System.out.println(user3.toString());
        
        
    }

}

 

posted @ 2018-11-27 22:00  知识追求者  阅读(196)  评论(0编辑  收藏  举报