简体   繁体   中英

Java Reflection - Get all instance variable names of a class

I'm writing an android app that requires binding a JSON object into a domain entity with the keys from the JSON as instance variables. Since there are several domain entities, each with different instance variables that the JSON needs to bind to in the app, i'd like to write a method such as ths following:

  1. Loop through all the instance variables from the domain
  2. if a key exists in the JSON with the name of the instance variable, take the value for this key from the JSON and set the Domain's instance variable with this key name equal to this value.

The reason i'm interested in the doing the binding from the class to the JSON is because if the JSON changes for some reason, I don't want it to break the app when the instance variable doesn't exist in the app's domain for a specific JSON key.

Thanks in advance for any help!

Most likely you want to use a json library that does this for you. Jackson is a good one that is also used by Spring MVC.

To answer your question, you can use getDeclaredFields() on a class, and use java.lang.reflect.Modifier.isStatic() to check if the field is static.

private static class Foo {
    private static long car;
    private int bar;
    private String baz;
}

public static void main(String[] args) {
    for (Field field : Foo.class.getDeclaredFields()) {
        if (!Modifier.isStatic(field.getModifiers())) {
            System.out.println("Found non-static field: " + field.getName());                
        }
    }
}

This will print out:

Found non-static field: bar
Found non-static field: baz

oksayt's answer is correct, but I'd take it with a grain of salt. Not every field holds a property that should be exposed publically. The mechanism to use is the Java Beans Introspector . You can use my answers to these previous Questions as reference:

Additional Reference:

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