Java反射 调用传参

反射是java的一个特性,这一特性也使得它给了广大的第三方框架和开发过者很大的想像空间。

  通过反射,java可以动态的加载未知的外部配置对象,临时生成字节码进行加载使用,从而使代码更灵活!可以极大地提高应用的扩展性!

//测试方法    
 @Test
public void test01() {
Class p = null;
Person01 person01 = new Person01();
try {
p = Class.forName("pojo.Person01");
// 第一个参数是类的方法名 第二个是需要传的参数
Method method = p.getMethod("returnName", String.class);
String aa = (String) method.invoke(person01, "123");
Method method2 = p.getMethod("returnId", Integer.class);
String bb = (String) method2.invoke(person01, 123);
// 多个参数
Class [] argTypes = new Class[2];
argTypes[0]= String.class;
argTypes[1] = Integer.class;
Method methods = p.getDeclaredMethod("getDouble",Integer.class,String.class);
Object [] objects = new Object[2];
objects[0] = "test";
objects[1] = 123;
String cc = (String) methods.invoke(person01,123,"123");

System.out.println(aa);
System.out.println(bb);
System.out.println(cc);
} catch (Exception e) {
e.printStackTrace();
}
}
 

 实体类

package pojo;

import lombok.Data;

/**
 * @author xulei
 * @version 1.0
 * @date 2020/4/28 16:03
 */
@Data
public class Person01 {public String  returnName(String string){
        return name+"___"+string;
    }
    
    public String returnId(Integer integer){
        return id+"___"+integer;
    }
    
    
    public String getDouble(Integer integer,String string){
        return string+"___"+integer;
    }
}
原文地址:https://www.cnblogs.com/lovetl/p/12795703.html