简体   繁体   English

如何通过 Java 反射获得存储在接口类型中声明的变量中的实现 class 的类型?

[英]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?如何通过 Java 反射获得存储在接口类型中声明的变量中的实现 class 的类型?

If you check the type of list variable declared as List type using getDeclaredField() , it will be obtained as List.如果您使用getDeclaredField()检查声明为List类型的列表变量的类型,它将作为 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?有没有办法将它作为 ArrayList 获得?

Of course not.当然不是。 That same variable could hold something entirely different, later;稍后,同一个变量可能会包含完全不同的东西; perhaps some code someplace will execute Test.list = new LinkedList<>() .也许某处的某些代码会执行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 .您可以简单地使用getClass()方法而不是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"
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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