See if field exists in class

后端 未结 6 1806
眼角桃花
眼角桃花 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: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 getAllFieldsSimpleNames(Class beanClass) {
        ArrayList fieldNames = new ArrayList();
        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, ArrayList> = ...
        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.

提交回复
热议问题