• 创建运行时类的对象,调用指定的属性方法构造器


    1 使用newInstance(),实际上是调用运行时空参的构造器

       注意构造器的权限修饰符要足够,同时必须有一个空参的构造器。

    2 调用指定的属性方法构造器

    package lianxi1;
    
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    import org.junit.Test;
    
    
    
    public class TestReflection2 {
        @Test
        public void test1() throws ClassNotFoundException, SecurityException, NoSuchFieldException, InstantiationException, IllegalAccessException {
            //1.获取运行类的属性
            String str = "lianxi1.Person";
            Class clazz = Class.forName(str);
            Field f1 = clazz.getField("name");
            //如果属性是private的
            Field f2 = clazz.getDeclaredField("age");
            f2.setAccessible(true);
           //2.创建运行类的对象
            Object obj = clazz.newInstance();
            Person p = (Person)obj;
            System.out.println(p);
           //3.对属性赋值
            f1.set(p, "tian");
            f2.set(p, 25);
            System.out.println(p);
        }
        @Test
        public void test2() throws ClassNotFoundException, SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
            //2.调用运行时类中指定的方法
            Class clazz = Person.class;
            Method m1 = clazz.getMethod("show");
            Person p1 = (Person)clazz.newInstance();
            Object obj = m1.invoke(p1);   //如果是静态方法改为 m1.invoke(Person.class)
            System.out.println(obj);
            
            Method m2 = clazz.getDeclaredMethod("display",String.class,int.class);
            m2.setAccessible(true);
            Object obj2 = m2.invoke(p1,"yu",22);
            System.out.println(obj2);
        }
        @Test
        public void test3() throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException{
            //3.调用制定的构造器,创建运行时类的对象
            Class clazz = Person.class;
            Constructor con = clazz.getDeclaredConstructor(String.class,int.class);
            con.setAccessible(true);
            Person p2 = (Person)con.newInstance("wuming",21);
            System.out.println(p2);
            
        }
    }
  • 相关阅读:
    高效的团队必须坚持反馈制度
    项目管理式生活
    用PDCA让工作效率步步高升
    PHP函数:fsockopen简介
    php的getallheaders函数在nginx下失效的解决办法
    getallheaders函数使用方法
    PHP中getenv函数
    PHP获取http请求的头信息实现步骤
    php下获取http状态的实现代码
    PHP获取客户端和服务器端IP
  • 原文地址:https://www.cnblogs.com/yjtm53/p/4166043.html
Copyright © 2020-2023  润新知