user3586195
user3586195

Reputation: 498

Pass a class parameter and return an object of that class (java)

I have a public method. The public method is declared as

public Object createUIBean(Class c, HttpServletRequest request) {
  Object o = c.newInstance() ;
  setRequestParams(o, request) ;
  return o ;
} // try catch block omitted for reasons of brevity

When calling this method, I have to cast the return result. Is there way I can write this method so I do not need to cast the returned object.

Upvotes: 0

Views: 71

Answers (2)

Pshemo
Pshemo

Reputation: 124225

I am not sure if that is what you want but maybe you are looking for something like generic method

public <T> T createUIBean(Class<T> c, HttpServletRequest request) {
  T o = c.newInstance() ;// "Class.forName(c.getName())" is equivalent of "c"
  setRequestParams(o, request) ;
  return o ;
} 

Now returned type T will be based on type T used as Class<T> c argument.

Upvotes: 3

rgettman
rgettman

Reputation: 178263

You can make the method generic, and you can use the generic type parameter as the return type and the type parameter for the type of the parameter c, Class (which is currently raw).

public <T> T createUIBean(Class<T> c, HttpServletRequest request) {
  T o = c.newInstance();
  setRequestParams(o, request) ;
  return o ;
} 

Also, Class.forName(c.getName()).newInstance() ; is too much to create a simple instance when c.newInstance() will do the job.

Upvotes: 5

Related Questions