使用类型参数访问私有构造函数

使用类型参数访问私有构造函数

本文介绍了Java:使用类型参数访问私有构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于的跟进。



假设我有以下类:

  class Foo< T> 
{
private T arg;
private Foo(T t){
// private!
this.arg = t;
}

@Override
public String toString(){
return我的参数是:+ arg;
}
}

如何构建







根据,以下工作:

  public class示例{
public static void main(final String [] args)throws Exception {
构造函数< Foo>构造函数
constructor = Foo.class.getDeclaredConstructor(Object.class);
constructor.setAccessible(true);
Foo< String> foo = constructor.newInstance(arg1);
System.out.println(foo);
}
}


解决方案

将需要获取类,找到构造函数,它接受一个单一的参数与T的下限(在这种情况下,对象),强制构造函数是可访问的(使用 setAccessible 方法),最后使用所需的参数调用它。


This is a followup to this question about java private constructors.

Suppose I have the following class:

class Foo<T>
{
    private T arg;
    private Foo(T t) {
        // private!
        this.arg = t;
    }

    @Override
    public String toString() {
        return "My argument is: " + arg;
    }
}

How would I construct a new Foo("hello") using reflection?

ANSWER

Based on jtahlborn's answer, the following works:

public class Example {
    public static void main(final String[] args) throws Exception {
        Constructor<Foo> constructor;
        constructor = Foo.class.getDeclaredConstructor(Object.class);
        constructor.setAccessible(true);
        Foo<String> foo = constructor.newInstance("arg1");
        System.out.println(foo);
    }
}
解决方案

you would need to get the class, find the constructor which takes a single argument with the lower bound of T (in this case Object), force the constructor to be accessible (using the setAccessible method), and finally invoke it with the desired argument.

这篇关于Java:使用类型参数访问私有构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 07:11