简体   繁体   中英

How to get the packagename of fields by reflection?

I'd like to detect fields in my class that either are custom fields (like Address or are native java fields.

Therefore I'm trying to read the package name of each field (to later check if they start with java.* .

public class ReflectionTest {
    public class MyDTO {
        private String name;
        private Address address;
    }

    public class Address {
        private String street;
        private String zip;
        private String town;
    }


    @Test
    public void testPackageName() {
        for (Field field : MyDTO.class.getDeclaredFields()) {
            //always: java.lang.Class
            System.out.println(field.getGenericType().getClass().getPackage().getName()); 
        }
    }
}

Problem: the package shown is always java.lang . Why?

You have to call getType() instead of getGenericType() . Consider this example:

public class Sandbox {

    public int intField;
    public Sandbox myField;

    public static void main(String[] args) {
        Arrays.stream(Sandbox.class.getDeclaredFields()).forEach(f ->
                System.out.println(f.getName() + " : " + f.getType().getName()));

    }
}

Output

intField : int
myField : my.answer.Sandbox

java.lang is a package that is imported implicitly on any Java class. That's why you can reference many classes contained in it (Like Object, or String), without including any import in your source.

However, nothing prevents you or anyone from creating a package named java.lang and including your own classes in it. So this is not a practical way to distinguish native Java (whatever you think this is) from custom fields.

I think you should also find out the classloader that loaded each particular class you're testing.

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