See if field exists in class

后端 未结 6 1854
眼角桃花
眼角桃花 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: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
    }
    

提交回复
热议问题