通过反射 根据指定类名创建对象 带参 不带参

1、不带参数的情况

首先得到该类的Class对象,再调用newInstance方法即可得到空参数列表的实例

public static void main(String[] args) throws Exception {
    Class c = Class.forName("com.nosuchmethod.Person"); //包名为com.nosuchmethod
    Method m = c.getMethod("test"); //Person有一个方法为test
    m.invoke(c.newInstance()); //调用test方法
}

输出结果为:

通过反射 根据指定类名创建对象 带参 不带参_第1张图片

2、带参数传递的情况

    public static void main(String[] args) throws Exception {
        Class clazz = Class.forName("com.nosuchmethod.Person");
        Method[] methods = clazz.getMethods();
        methods = clazz.getDeclaredMethods();
        Person p = (Person) clazz.newInstance();
        Method method = clazz.getMethod("test", TestEnt.class);
        TestEnt testEnt = new TestEnt();
        testEnt.setName("KingHao");
        TestEnt a = (TestEnt) method.invoke(p, testEnt);
        System.out.println(a.getName());
    }

输出结果为:

通过反射 根据指定类名创建对象 带参 不带参_第2张图片

 

 

Person 类:
import com.cloud.TestEnt;
public class Person {


    public String test(String obj) {
        System.out.println(obj);
        return obj;
    }

    public TestEnt test(TestEnt obj) {
        System.out.println("这是带参数的方法");
        return obj;
    }

    public void test() {
        System.out.println("这是不带参数的方法");
    }


}

 

TestEnt类:
package com.cloud;

import lombok.Data;

/**
 * @author kinghao
 * @version 1.0
 * @className TestEnt
 * @description
 * @date 2020/6/9   18:51
 * @description
 */
@Data
public class TestEnt {
    private String name;
}

 

 

 

参考文章:https://blog.csdn.net/u010729348/article/details/16819693

你可能感兴趣的:(java,java,反射)