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

I want to return an instance of an object of the type of the incoming class object The type passed in can be arbitrary Is there any way to use generics?

Clarification – I don't want method callers to have to convert to the class of the object they pass 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);

Solution

I suppose you want to create a new instance of the class It's impossible to use generics (you can't call new t ()), and it will be quite limited to use reflection

Reflection methods can 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 is only valid if the class has a parameterless constructor

However, the question is why you need to call the new whateverclassyouhave()

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>