How can I get the type of the implementation class stored in the variable declared in the interface type by Java reflection?
If you check the type of list variable declared as List type using getDeclaredField(), it will be obtained as List.
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class Test {
private static List<String> list = new ArrayList<>();
public static void main(String[] args) throws Exception {
Field f = Test.class.getDeclaredField("list");
String type = f.getType().getSimpleName();
System.out.println(type); //output "List"
}
}
Is there a way to get it as an ArrayList?
>Solution :
You can simply use getClass() method instead of reflection.
import java.util.ArrayList;
import java.util.List;
public class Test {
private static List<String> list = new ArrayList<>();
public static void main(String[] args) throws Exception {
System.out.println(list.getClass().getSimpleName()); //ArrayList
}
}
Using reflection its possible. You need to read the type of the value assigned to the variable:
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class Test {
private static List<String> list = new ArrayList<>();
public static void main(String[] args) throws Exception {
Field f = Test.class.getDeclaredField("list");
String type = f.get(new Object()).getClass().getSimpleName();
System.out.println(type); //output "ArrayList"
}
}