Java泛型和反思!

Jay*_*Jay 4 java generics reflection

我有一个看起来像这样的课程:

public class UploadBean {


    protected UploadBean(Map<String,?> map){ 
        //do nothing.
    }
}
Run Code Online (Sandbox Code Playgroud)

要通过调用相应的构造函数来使用反射并创建对象,我编写了如下代码:

Class<?> parTypes[] = new Class<?>[1];
parTypes[0] = Map.class;
Constructor ct = format.getMappingBean().getConstructor(parTypes);
Object[] argList  = new Object[1];
argList[0] = map;
Object retObj = ct.newInstance(argList);
Run Code Online (Sandbox Code Playgroud)

此代码在运行时因"无此方法异常"而失败.现在,如何正确设置参数类型?!这样可以识别构造函数中的泛型map参数?

Jon*_*eet 7

构造函数受到保护 - 如果您将其公开使用getDeclaredConstructor而不是getConstructor它应该工作.

(setAccessible如果你试图从通常无法访问的地方调用它,你需要使用它.)

编辑:这是一个测试,以显示它工作正常:

import java.lang.reflect.*;
import java.util.*;

public class UploadBean {

    // "throws Exception" just for simplicity. Not nice normally!
    public static void main(String[] args) throws Exception {
        Class<?> parTypes[] = new Class<?>[1];
        parTypes[0] = Map.class;
        Constructor ct = UploadBean.class.getDeclaredConstructor(parTypes);
        Object[] argList  = new Object[1];
        argList[0] = null;
        Object retObj = ct.newInstance(argList);
    }

    protected UploadBean(Map<String,?> map){ 
        //do nothing.
    }
}
Run Code Online (Sandbox Code Playgroud)