Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

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

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...