Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

java - Pass class type as parameter to use in ArrayList?

I need to write a java method which takes a class (not an object) and then creates an ArrayList with that class as the element of each member in the array. Pseudo-code example:

public void insertData(String className, String fileName) {
      ArrayList<className> newList = new ArrayList<className>();
}

How can I accomplish this in Java?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use Generic methods

public <T> void insertData(Class<T> clazz, String fileName) {
   List<T> newList = new ArrayList<>();
}

but if you should use this contract insertData(String className, String fileName), you cannot use generics because type of list item cannot be resolved in compile-time by Java.

In this case you can don't use generics at all and use reflection to check type before you put it into list:

public void insertData(String className, String fileName) {
    List newList = new ArrayList();

    Class clazz;
    try {
        clazz = Class.forName(className);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e); // provide proper handling of ClassNotFoundException 
    }

    Object a1 = getSomeObjectFromSomewhere();

    if (clazz.isInstance(a1)) {
        newList.add(a1);
    }
    // some additional code
}

but without information of class you're able use just Object because you cannot cast your object to UnknownClass in your code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...