简体   繁体   中英

How can I get the type of the implementation class stored in the variable declared in the interface type by Java reflection?

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?

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.

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"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM