See if field exists in class

后端 未结 6 1805
眼角桃花
眼角桃花 2021-02-03 21:47

I have a class with various variables

public class myClass{

    public int id;
    public String category;
    public String description;
    public String star         


        
相关标签:
6条回答
  • 2021-02-03 22:22

    Warning: the accepted answer will work, but it relies on exceptions as control flow, which is bad practice and should be avoided wherever possible.

    Instead, consider the following alternative:

    public boolean doesObjectContainField(Object object, String fieldName) {
        Class<?> objectClass = object.getClass();
        for (Field field : objectClass.getFields()) {
            if (field.getName().equals(fieldName)) {
                return true;
            }
        }
        return false;
    }
    

    Or a more succinct form using Java 8 streams:

    public boolean doesObjectContainField(Object object, String fieldName) {
        return Arrays.stream(object.getClass().getFields())
                .anyMatch(f -> f.getName().equals(fieldName));
    }
    

    These code snippets do not rely on exceptions as control flow and in fact do not require any exception handling at all, which will make your implementation simpler and more readable. You would just call one of the methods above with a piece of code similar to the following:

    Object someObject = ... ;
    boolean fieldExists = doesObjectContainField(someObject, "foo");
    

    As a side note, if you needed to access the private fields of your class (but not parent class fields), you could simply replace the call to getFields by getDeclaredFields.

    0 讨论(0)
  • 2021-02-03 22:23

    Your compiler usually knows that pretty well, and the runtime lets you examine loaded classes with reflection.

    Object someObject = ...
    Class<?> someClass = someObject.getClass();
    Field someField = someClass.getField("foo");
    

    The getField() method will throw an exception if the field can not be found.

    0 讨论(0)
  • 2021-02-03 22:23

    This is a bit inconvenient to do in single step.

    When we moved to polymorphism concept there are challenges like generating lacks of objects for a Class(ABC Class) taking data dynamically by referencing other dedicated Classes(ABCXMLDOMnodes Class, ABCHTMLDOMnodes Class) which contains same fields but static and final type. Hope you got the requirement.

    1.Creating ArrayList of fields Simple names of these three class as global.

     private static ArrayList<String> getAllFieldsSimpleNames(Class<?> beanClass) {
        ArrayList<String> fieldNames = new ArrayList<String>();
        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            fieldNames.add(field.getName());
        }
        return fieldNames;
    }
    

    2.And then every time of generating an object we are validating fields(say >10 fields) against helper classes like below is easy i feel.

     for(String a :abcFieldNames){
            if(abcXMLfieldnames.contains(a)){
            //code here
            }else if(abcHTMLfieldnames.contains(a){
            //code here
            }
        }
    

    Other simplest and dynamical way is creating

          HashMap<Class<?>, ArrayList<String>> = ...
        hm.put(ABC.class, getAllFieldsSimpleNames(ABC.class));
        hm.put(ABCXMLDOMnodes.class, getAllFieldsSimpleNames(ABCXMLDOMnodes.class));
    if(hm.get(ABCXMLDOMnodes.class).contains("a"){...}
    

    My suggestion to Oracle Corp. JAVA network is if "Class class" can provide a method that returns a list of field names of given Class as string type only will be helpful.

    0 讨论(0)
  • 2021-02-03 22:28

    You can do it using reflection, though I would recommend to check if it is really needed or maybe there's another way to do it.

    For example:

    Class<?> clz = MyClass.class;
    try {
        Field f = clz.getField("foo")
    }
    catch ( NoSuchFieldException ex) {
        // field doesn't exist
    }
    catch (SecurityException ex) {
        // no access to field
    }
    
    0 讨论(0)
  • 2021-02-03 22:29

    What you are looking for is called "Reflection". It provides the ability at run-time to determine what fields and methods are contained within a class.

    http://today.java.net/pub/a/today/2008/02/12/reflection-in-action.html

    0 讨论(0)
  • 2021-02-03 22:33

    As others already mentioned reflection is what you need.

    If you need to access a private field you can use Class.getDeclaredField(String name)

    0 讨论(0)
提交回复
热议问题