0
点赞
收藏
分享

微信扫一扫

javase:反射对象

芷兮离离 2022-01-07 阅读 33
java
import java.lang.reflect.Constructor;

/*
使用反射机制创建对象
 */
public class ReflectNew {
    public static void main(String[] args) throws Exception{
        Class c = Class.forName("com.Vip");

        // 调用无参构造方法,第13行代码和第14-15行代码功能相同。
        // Object noObj = c.newInstance();
        Constructor noC = c.getDeclaredConstructor();
        Object noObj = noC.newInstance();
        System.out.println(noObj);

        // 调用有参构造方法,先获取到这个有参构造方法,再传参数new对象。
        Constructor haveC = c.getDeclaredConstructor(int.class, String.class, String.class, boolean.class);
        Object haveObj = haveC.newInstance(001, "zhangsan", "2000-1-1", true);
        System.out.println(haveObj);

    }
}

class Vip {
    int no;
    String name;
    String birth;
    boolean sex;

    public Vip() {
    }

    public Vip(int no, String name, String birth, boolean sex) {
        this.no = no;
        this.name = name;
        this.birth = birth;
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Vip{" +
                "no=" + no +
                ", name='" + name + '\'' +
                ", birth='" + birth + '\'' +
                ", sex=" + sex +
                '}';
    }
}
举报

相关推荐

【javaSE】反射

Javase 反射机制

javase:反射注解

JavaSE:注解和反射

【JavaSE总结】注解和反射

javase:反射方法的操作

JAVASE:方法、对象

JavaSE面向对象

0 条评论