mercredi 10 août 2016

NullPointerException while using this.getClass().getDeclaredField method

I wanted to get only one field name of a POJO, my java POJO look like:

public class A1 {

    private String field1;

    public String getField1() {
        return field1;
    }

    public void setField1(String field1) {
        this.field1 = field1;
    }

    @Override
    public String toString() {
        return "A1 [field1=" + field1 + "]";
    }

    public String getFiled1Name() throws NoSuchFieldException, SecurityException{
        return this.getClass().getDeclaredField(field1).getName();
    }

}

In the client code:

System.out.println(new A1().getFiled1Name());

I am getting NullPointerException

I tried method this.getClass().getDeclaredFields() and this works as expected. But the problem with this is: It returns all the fields(java.lang.reflect.Field) and I need to iterate, compare and then return the correct filed name.

Rather I want to get only one field name. How I can get this?





Aucun commentaire:

Enregistrer un commentaire