简体   繁体   中英

Passing in a Type reference to a method

I want to write a method that will create a List of the type I define in the method parameters. So if I have 3 classes: Student , Teacher and Janitor , the method should create a List of whatever type is passed in

public void methodName(TYPE){  
    List<TYPE> results = new List<TYPE>();  
}

What should I be using for TYPE ?

You can use JAVA generics. One way is to allow all class types to be acceptable, by this..

public <T> void methodName(Class<T> cl){  
    List<T> results = new ArrayList<T>();  
}

or a better way would be to make all classes you want to be accepted derive from an interface, say Person and then you can do..

public <T extends Person> void methodName(Class<T> cl){  
    List<T> results = new ArrayList<T>();  
}

This limits the set of classes accepted by the the method, to only those implementing Person .

It's not entirely clear what you want, but one option is as follows:

public <T>
void methodName(Class<T> clazz) {

    List<T> results = new ArrayList<T>();
    ...
}

You could then call it as:

methodName(Student.class);

If these three classes can inherit from a single class or implement a single interface then your method signature can be like this:

public List<ParentClass/Interface> methodName(TYPE);

If three class cannot be related to a common contract as mentioned above then other choice will be to return the list of Objects and cast the objects appropriately when you iterate the list of objects:

public List<Object> methodName(TYPE);

You may want to check out a question of mine , which, however, approaches the issue from the other side.

Basically Java has such a function already (feel free to go from there):

Collections.<String>emptyList()

to get an empty List with elements which are supposedly of type String. Java's source looks like this:

public static final List EMPTY_LIST = new EmptyList<Object>();
:
public static final <T> List<T> emptyList() {
  return (List<T>) EMPTY_LIST;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM