0

For example, is it possible to do something like this:

public void doSomething(Class clazz) { List<clazz> list = new ArrayList<clazz>(); list.add(clazz.newInstance)); } 

I know this doesn't work, but it shows what I'm trying to get at. Is there any way to parameterize the creation of generic class?

Thanks, Peter

3
  • Why? What would you do with the list? Commented Feb 4, 2011 at 15:33
  • How will you decide what to do with the stuff inside other than with instanceof? Commented Feb 4, 2011 at 15:34
  • The list is just an example of the kind of mechanics I am trying to use. The real application is different. Commented Feb 4, 2011 at 16:02

1 Answer 1

6

You can try

public <T> void doSomething(Class<T> clazz) { List<T> list = new ArrayList<T>(); list.add(clazz.newInstance()); } 
Sign up to request clarification or add additional context in comments.

2 Comments

public <T> void doSomething(Class<? extends T> clazz) { would probably be more useful. Although reflection is quite evil.
@Tom, it would be more useful if the method did something with the list (might be a good idea too) ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.