Java泛型的问题 [英] Java generics question

查看:80
本文介绍了Java泛型的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以编写一个可以创建任何指定类型实例的方法?



我认为java泛型应该有所帮助,所以它可能是这样的:

/ p>

  public< U> U getObject(Class klass){
// ...
}

任何人都可以帮助我吗?

解决方案

  public< U> U genericFactory(构造函数< U> classConstructor,Object.args)
throws
InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
return classConstructor。的newInstance(参数);

$ / code>

您可以从 Class< U> ;通过 getConstructors 方法对象。通过构造函数本身,您可以获得有关参数的信息,所以需要在该工厂外部添加一些额外的代码来适当地填充参数。



显然,这只是就像彼得的答案一样丑陋。

Is it possible to write a method that could create instances of any specified type?

I think java generics should help, so it might be something like this:

    public <U> U getObject(Class klass){
        //...
    }

Could anyone help me?

解决方案

 public <U> U genericFactory(Constructor<U> classConstructor, Object..args)
  throws
   InstantiationException,
   IllegalAccessException,
   IllegalArgumentException,
   InvocationTargetException {
     return classConstructor.newInstance(args);
 }

You can get a constructor from a Class<U> object via the getConstructors method. Via the constructor itself you can get information about the arguments, so there needs to be some extra code outside this factory to fill in the arguments appropriately.

Obviously, this is just as ugly as Peter's answer.

这篇关于Java泛型的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆