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?
You can pass the class as parameter.
In Java, we can pass a reference to an object (also called a "handle")as a parameter. We can then change something inside the object; we just can't change what object the handle refers to.
If we want to pass an ArrayList as an argument to a function then we can easily do it using the syntax mentioned below. In the code above, we created an ArrayList object named 'list' and then we passed it to a function named modifyList.
The syntax for declaring an ArrayList of objects is as follows: ArrayList<ClassName> arrayListName; Inside angle brackets, we declare the class types of objects that will be stored in ArrayList. Let's understand with the help of some examples.
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.
My guess is that what you really want to do is to return the generated List
. This is what that might look like:
public <T> List<T> loadData(Class<T> clazz, String fileName) {
List<T> newList = new ArrayList<>();
//...populate list somehow (e.g. with values deserialized from the file named "filename")
return newList;
}
This is how it could be used:
List<String> names = loadData(String.class, "someFileContainingNameStrings");
List<Double> temperatures = loadData(Double.class, "someFileContainingTemperatureData");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With