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?
CodePudding user response:
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"
}
}
CodePudding user response:
Of course not. That same variable could hold something entirely different, later; perhaps some code someplace will execute Test.list = new LinkedList<>()
. What you want to know is unanswerable.
Perhaps you'd want to dig into the assigning expression but that's no joy either. Behold:
private static List<String> list = Math.random() > 0.5 ?
new LinkedList<>() :
new ArrayList();
You see how this just isn't a question that has a meaningful answer.