jeudi 14 juin 2018

java reflections to get all user created class variables only

I am trying to use reflections to create a function that checks all custom made class variables to see if they have valid values based on pattern "[0-9a-zA-Z_]+"

I found some code templates and adapted to my code and looks like this

UserClass uc = new UserClass();
Class clazz = uc.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String name = field.getName();
                Object value;
                try {
                    value = field.get( uc );
                     System.out.printf("Field name: %s, Field value: %s%n", name, value);
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }

My UserClass looks like

@Entity
public class UserClass implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;

    private String descr;

    private String name;

    @OneToMany(mappedBy="userClassId",fetch=FetchType.LAZY)
    private List<packages> packagesList;

I get the UserClass variable names and values normally but the problem is that it also takes some other variables which i dont care about like pcInheritedFieldCount,pcFieldNames and others

My solution is to check if the variable name starts if pc to ignore it but i wanted to know if there is a right/the best way to get only these variables i declared in my class definition.





Aucun commentaire:

Enregistrer un commentaire