调用运行时类的指定属性,方法,构造器

1. 调用运行时类的指定属性

2. 调用运行时类的指定的方法

3. 调用指定的构造器,创建运行时类的对象

TestField1

package com.aff.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.junit.Test;

public class TestField1 {
    // 调用运行时类的指定属性

    @Test
    public void test1() throws Exception {
        Class clazz = Person.class;
        // 1.获取指定属性
        // getField(String fieldName):获取运行时类中声明为public的指定属性名为fieldName的属性
        Field name = clazz.getField("name");
        // 2.创建运行时类的对象
        Person p = (Person) clazz.newInstance();
        System.out.println(p);
        // 3.将运行时类的指定的属性赋值
        name.set(p, "Jerry");
        System.out.println(p);
        System.out.println();

        // getDeclaredField:获取运行时类中指定属性名为fieldName的属性
        Field age = clazz.getDeclaredField("age");
        // 由于属性权限修饰符的限制,为了保证可以给属性赋值,需要在操作前使得此属性可被操作
        age.setAccessible(true);
        age.set(p, 10);
        System.out.println(p);

        // Field id = clazz.getField("id");
    }

    
    // 调用运行时类的指定的方法
    @Test
    public void test2() throws Exception {
        Class clazz = Person.class;
        // getMethod(String methodName,Class ... params):获取运行时类中声明为public的方法
        Method m1 = clazz.getMethod("show");
        Person p = (Person) clazz.newInstance();
        // 调用指明的方法: Object invoke(Object obj, Object...obj );
        // 又返回值的,show的返回值就是invoke的返回值
        Object returnVal = m1.invoke(p);// 不带返回值,调用p对象,打印输出 得即高歌失即休
        System.out.println(returnVal);// null

        Method m2 = clazz.getMethod("toString");
        Object returnVal1 = m2.invoke(p);// 带返回值的,不打印看不见输出的
        System.out.println(returnVal1);// Person [name=null, age=0]
        // 对于运行时类中静态方法的调用
        Method m3 = clazz.getMethod("info");
        /* Object returnVal2 = */m3.invoke(Person.class);// 唐宋三大家

        // getDeclaredMethod(String methodName,Class ... params):获取运行时类中声明的指定方法
        Method m4 = clazz.getDeclaredMethod("display2", String.class);// 有一个参数的
        m4.setAccessible(true);
        /* Object returnVal3 = */m4.invoke(p, "晚唐");// 多愁多恨亦悠悠 
 晚唐
    }

    
    
    // 调用指定的构造器,创建运行时类的对象
    @Test
    public void test3() throws Exception {
        Class clazz = Person.class;
        Constructor cons = clazz.getDeclaredConstructor(String.class, int.class);
        cons.setAccessible(true);
        Person p = (Person) cons.newInstance("罗隐", 33);
        System.out.println(p);// Person [name=罗隐, age=33]
    }
}
All that work will definitely pay off
原文地址:https://www.cnblogs.com/afangfang/p/12624822.html