Java generic problem
•
Java
Can I write a method that can create an instance of any specified type?
I think Java generics should help, so it might be like this:
public <U> U getObject(Class klass){ //... }
Who can help me?
Solution
public <U> U genericFactory(Constructor<U> classConstructor,Object..args)
public <U> U genericFactory(Constructor<U> classConstructor,Object..args) throws InstantiationException,illegalaccessexception,IllegalArgumentException,InvocationTargetException { return classConstructor.newInstance(args); }
You can get the constructor from class < U > Object through getconstructors method You can get information about the parameters through the constructor itself, so you need to add some additional code outside this factory to fill the parameters appropriately
Obviously, this is as ugly as Peter's answer
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
二维码