如何返回与使用Java 6传入的类相同类型的对象的实例? [英] How do I return an instance of an object of the same type as the class passed in using Java 6?

查看:193
本文介绍了如何返回与使用Java 6传入的类相同类型的对象的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想返回一个与传入的Class对象类型相同的对象的实例。传入的类型可以是ANYTHING。有没有办法与泛型做到这一点?



澄清 - 我不希望方法的调用者不必转换为对象的类例如,

  public Object< Class> getObject(Class class)
{
//构造一个Class类型的对象的实例

return object;
}

//我想要:
MyClass myObj = getObject(MyClass.class);

//不是(铸造):
MyClass myObj =(MyClass)getObject(MyClass.class);


解决方案

我假设您要创建一个新的实例类。这不可能使用泛型(你不能调用 new T()),并且使用反射也会受到很大限制。



反射方法可以是:

  // class是一个保留字,所以使用clazz 
公共< T> T getObject(Class< T> clazz){
try {
return clazz.newInstance();
}
catch(/ *可由clazz.newInstance()* /){
//处理异常
}
} $引发的大量异常b $ b

请注意,这只适用于类没有参数构造函数的情况。



然而,问题出在你为什么需要而不是仅仅调用
new WhatEverClassYouHave()


I want to return an instance of an object of same type of the Class object passed in. The type passed in can be ANYTHING. Is there a way to do this with Generics?

To clarify -- I don't want the caller of the method to not have to cast to the Class of the object they passed in

For example,

public Object<Class> getObject(Class class)
{
  // Construct an instance of an object of type Class

  return object;
}

// I want this:
MyClass myObj = getObject(MyClass.class);

// Not this (casting):
MyClass myObj = (MyClass)getObject(MyClass.class);

解决方案

I assume you want to create a new instance of that class. This would not be possible using generics (you can't call new T()) and would also be quite limited using reflection.

The reflection approach could be:

//class is a reserved word, so use clazz
public <T> T getObject(Class<T> clazz) {
  try {
    return clazz.newInstance();
  }
  catch( /*a multitude of exceptions that can be thrown by clazz.newInstance()*/ ) {
    //handle exception
  }
}

Note that this only works if the class has a no-argument constructor.

However, the question would by why you need that instead of just calling
new WhatEverClassYouHave().

这篇关于如何返回与使用Java 6传入的类相同类型的对象的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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