Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading