如何返回与使用 Java 6 传入的类相同类型的对象的实例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9790908/
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-08-16 07:41:01  来源:igfitidea点击:

How do I return an instance of an object of the same type as the class passed in using Java 6?

javagenerics

提问by BestPractices

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?

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

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

采纳答案by Thomas

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.

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

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().

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

回答by manub

public Object getObject(Class clazz) {
  return clazz.newInstance();
}

Will create a new object of the specified class. You don't have to use generics for this.

将创建指定类的新对象。您不必为此使用泛型。

回答by Puce

You don't have to implement this method, it's already there:

您不必实现此方法,它已经存在:

http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#newInstance%28%29

http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#newInstance%28%29

Usage:

用法:

Class<T> type = ...;
T instance = type.newInstance();

回答by Java42

public <C> C getObject(Class<C> c) throws Exception 
{ 
    return c.newInstance(); 
}

Usage Example:

用法示例:

static <C> C getObject(Class<C> c) throws Exception { 
    return c.newInstance();
}

static class Testing {
    {System.out.println("Instantiated");}
    void identify(){ System.out.println("Invoked"); }
}

public static void main(String args[]) throws Exception {
    Testing t = getObject(Testing.class);
    t.identify();
}

回答by akousmata

If you aren't trying to do anything fancy with the object during the creation, what's wrong with just using a good old fashioned constructors?

如果您在创建过程中不想对对象做任何花哨的事情,那么仅使用良好的老式构造函数有什么问题呢?

You should be able to use something similar to:

您应该能够使用类似于以下内容的内容:

public T getObject<T>(T obj)
{
  return obj.newInstance();
}