开发者

See if field exists in class

I have a class with various variables

public class myClass{

    public int id;
    public开发者_开发技巧 String category;
    public String description;
    public String start;
    public String end;
}

Is there a way to check, either by creating an internal function or checking from the calling object, whether or not a variable exists?

E.g. To check whether myClass contains a variable called "category" (it does). Or whether it contains a category called "foo" (it does not).


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.


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.


As others already mentioned reflection is what you need.

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


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
}


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜