java Java泛型和反射!

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/939903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:28:12  来源:igfitidea点击:

Java Generics and reflection!

javagenericsreflection

提问by Jay

I have a class that looks like this:

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

public class UploadBean {


    protected UploadBean(Map<String,?> map){ 
        //do nothing.
    }
}

To use reflection and create a object by invoking the corresponding constructor, I wrote code as follows:

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

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);

This code fails at runtime with "No Such Method Exception". Now, how do I set the param type correctly?! such that the generic map argument in the constructor is identified?

此代码在运行时失败,并显示“无此类方法异常”。现在,如何正确设置参数类型?!以便识别构造函数中的通用映射参数?

回答by Jon Skeet

The constructor is protected - if you make it public oruse getDeclaredConstructorinstead of getConstructorit should work.

构造函数是受保护的 - 如果您将其公开使用它getDeclaredConstructor来代替getConstructor它应该可以工作。

(You'll need to use setAccessibleif you're trying to call this from somewhere you wouldn't normally have access.)

setAccessible如果您尝试从通常无法访问的地方调用它,则需要使用。)

EDIT: Here's a test to show it working okay:

编辑:这是一个测试,表明它可以正常工作:

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.
    }
}

回答by fortran

The generic information is not available at runtime, it's just for static analysis, so do it as if the generics didn't exist.

泛型信息在运行时不可用,它只是用于静态分析,所以就好像泛型不存在一样。

回答by Rob Di Marco

I believe you need to call

我相信你需要打电话

ct.setAccessible(true)

The setAccessible method allows you to override access methods.

setAccessible 方法允许您覆盖访问方法。