Home » Java » java – Can we pass class name as parameter?-Exceptionshub

java – Can we pass class name as parameter?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:
private void passClassName(String className) {
    JSONArray jsonArray = <ReadSomeJsonFile>;
    String dataSet = jsonArray.toString();
    List<className> testData = new Gson().fromJson(dataSet, new TypeToken<List<className>>() {}.getType()); 
}

Here I want to pass ClassName as parameter. But as that class will not be accessible with parameter. So it will not work. I already tried similar solutions. Nothing worked for me till now.

How to&Answers:

You cannot make this dynamic, with class given at runtime. For this to work, the compiler must be able to create an anonymous class for new TypeToken<List<MyClass>>() {}. That cannot be done at runtime.

Well, it can, but now you’re into dynamic bytecode creation at runtime, so let’s skip that super complex option. Ask another question if you want to explore that route.

Which means that the caller must create the TypeToken anonymous class, e.g. like this:

private <E> List<E> readJsonList(TypeToken<List<E>> typeToken) {
    JSONArray jsonArray = <ReadSomeJsonFile>;
    String dataSet = jsonArray.toString();
    List<E> testData = new Gson().fromJson(dataSet, typeToken.getType());
    return testData;
}

Caller

List<Integer> list = readJsonList(new TypeToken<List<Integer>>() {});