• 反射机制实例化类,并获取类中的属性、方法、和构造器


    1.先写一个JavaBean类:

    package com.buaa.reflectTest;

    public class User {
    private int id;
    private int age;
    private String uname;
    public int getId() {
    return id;
    }
    public void setId(int id) {
    this.id = id;
    }
    public int getAge() {
    return age;
    }
    public void setAge(int age) {
    this.age = age;
    }
    public String getUname() {
    return uname;
    }
    public void setUname(String uname) {
    this.uname = uname;
    }
    public User(int id, int age, String uname) {
    super();
    this.id = id;
    this.age = age;
    this.uname = uname;
    }
    public User() {
    }

    }

    2.利用反射机制获取do something....
    package com.buaa.reflectTest;

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

    public class Demo01 {
    public static void main(String[] args) {
    String path = "com.buaa.reflectTest.User";
    try {
    Class<User> clazz = (Class<User>)Class.forName(path);

    //get constructor
    Constructor con = clazz.getDeclaredConstructor(int.class,int.class,String.class);
    User u = (User)con.newInstance(1,19,"maomi");
    System.out.println(u.getUname());

    //get Method
    Method m = clazz.getDeclaredMethod("setAge", int.class);
    m.setAccessible(true);
    m.invoke(u, 20);
    System.out.println(u.getAge());

    //get field
    Field f = clazz.getDeclaredField("id");
    f.setAccessible(true); //设置访问权限
    f.set(u, 3);
    System.out.println(u.getId());

    } catch (Exception e) {
    e.printStackTrace(http://www.amjmh.com);
    }
    }
    }

    ---------------------

  • 相关阅读:
    DDD领域驱动设计初探(四):WCF搭建
    DDD领域驱动设计初探(三):仓储Repository(下)
    DDD领域驱动设计初探(二):仓储Repository(上)
    编译环境搭建:Makefile
    cuowu
    Angular4+路由
    由href return false 来看阻止默认事件
    TypeScript的配置文件 tsconfig.json
    Java标记接口
    new Date()前面使用 +发生了什么
  • 原文地址:https://www.cnblogs.com/hyhy904/p/11331568.html
Copyright © 2020-2023  润新知