zoukankan      html  css  js  c++  java
  • 创建运行时类的对象,调用指定的属性方法构造器

    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);
            
        }
    }
  • 相关阅读:
    实战体会Java的多线程编程
    java synchronized用法
    java thread代码
    java简单线程池实例代码
    visual studio 配色方案的设置及需注意的问题
    【转】 Response.Redirect(),Server.Transfer(),Server.Execute()的区别
    Button.PerformClick 仅支持winform,可模拟按钮点击
    Codeforces Round #118 (Div. 2) B题(Codeforces上不支持qsort,只支持sort!!!)
    hdu4324(拓扑排序&强连通)
    三分法——求解凸性函数的极值问题
  • 原文地址:https://www.cnblogs.com/yjtm53/p/4166043.html
Copyright © 2011-2022 走看看