简体   繁体   中英

Java Constructor List as string

I'm trying to populate an array list of strings with the name of the constructors for a class. For some reason it's getting populated with the class name instead

Class<?> c = Class.forName(className);
        Constructor<?>[] construct = c.getDeclaredConstructors();
        for(int i = 0; i < construct.length; i++){
            memberList.add(construct[i].getName());
        }

构造函数始终使用类的名称-这就是您所看到的。

如果要在列表中使用构造器对象而不是构造器对象的名称 ,则需要删除“ .getName()”

Like Sunil said, the constructor has the same name as the class and you should make the difference between them checking his params.

To get the params you could try the next code:

    public static void main(String[] args) throws ClassNotFoundException {
    Class<?> c = Class.forName(Class1.class.getCanonicalName());
    Constructor<?>[] constructors = c.getDeclaredConstructors();
    ArrayList<String> memberList = new ArrayList<String>();
    for(Constructor<?> constructor:constructors){
        memberList.add(constructor.getName());
        System.out.println("--------------------------------------");
        System.out.println(String.format("constructor: %s",new Object[]{constructor}));

        for(Class<?> paramType: constructor.getParameterTypes()){
            System.out.println(String.format("constructor param type: %s",paramType));
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM