Discuss / Java / Method无法实现Constructor的功能吗?

Method无法实现Constructor的功能吗?

Topic source

试了一下

import java.lang.reflect.Method;

public class Main {
    public static void main(String[] args) throws Exception {
        //以为会在下下句出现问题:invoke第一个参数不知道该怎么传了
        //但是第一句就会报错:Exception in thread "main" java.lang.NoSuchMethodException: java.lang.Integer.Integer(int)
        Method cons1 = Integer.class.getMethod("Integer",int.class);
        Integer n1 = (Integer) cons1.invoke(null,123);
        System.out.println(n1);
    }
}

木瑾深

#2 Created at ... [Delete] [Delete and Lock User]

getMethod(name,Class...)方法只能获取到类中public型的方法,无法获取public型的构造方法;

其实使用getMethods()方法打印下获取到的方法,就可以看见里面根本拿不到构造方法,只有普通的public方法。


  • 1

Reply