Use Pass class type as parameter for use in ArrayList?

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

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

How can I execute this in Java?

+5
source share
3 answers

You can use common methods

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

but if you must use this insertData(String className, String fileName) contract insertData(String className, String fileName) , you cannot use generics, because the type of the list item cannot be resolved during Java compilation.

In this case, you may not use generics at all and use reflection to check the type before adding it to the 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 class information, you can only use Object , because you cannot drop your object in UnknownClass in your code.

+4
source

Vlad Bochenen gives a good way, but it makes no sense to offer a swarm that has nothing to do with your method.
It places null constraints in the insertData() code, which manipulates the list.
You will be forced to throw code, and that defeats the goal of Generics.

I assume that you want to manipulate some instances of known classes in insertData() .
And if you use the generic in your case, it would be more meaningful if you have subtypes of classes to manipulate.

So you can have a method that accepts a base type and its subclasses.

 public static <T extends YourClass> void insertData(Class<T> clazz, String fileName) { List<T> newList = new ArrayList<>(); T t = newList.get(0); // here I can manipulate something that derives from YourClass } 
+2
source

I assume that you really want to return the generated List . Here's what it looks like:

 public <T> List<T> loadData(Class<T> clazz, String fileName) { List<T> newList = new ArrayList<>(); //...populate list somehow (eg with values deserialized from the file named "filename") return newList; } 

Here's how to use it:

 List<String> names = loadData(String.class, "someFileContainingNameStrings"); List<Double> temperatures = loadData(Double.class, "someFileContainingTemperatureData"); 
0
source

Source: https://habr.com/ru/post/1263878/


All Articles