lundi 25 février 2019

Get field value of non instantiable class - Reflection

How to iterate and get the value of all fields of a non instantiable class:

import java.lang.reflect.Field;

public class NonInstantiableClass {
    private Integer a1 = 1;
    private String a2 = "a";

    private NonInstantiableClass () {
         throw new AssertionError();
    }

    public static void printVariables () throws IllegalAccessException {

        for (Field field : NonInstantiableClass.class.getDeclaredFields()) {
            field.setAccessible(true);
            System.out.println(field.getName()
                    + " - " + field.getType()
                    + " - " + field.get(NonInstantiableClass.class));
        }
    }


    public static void main(String args[]) throws IllegalAccessException {
        NonInstantiableClass.printVariables();
    }
}

Given this code gets the following error:

Exception in thread "main" java.lang.IllegalArgumentException: Can not set java.lang.Integer field NonInstanciableClass.a1 to java.lang.Class
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
    at java.base/jdk.internal.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
    at java.base/java.lang.reflect.Field.get(Field.java:418)
    at NonInstanciableClass.printVariables(NonInstanciableClass.java:17)
    at NonInstanciableClass.main(NonInstanciableClass.java:23)

If the class were instantiable the same code works with an instance:

import java.lang.reflect.Field;

public class NonInstantiableClass {
    private Integer a1 = 1;
    private String a2 = "a";

    //private NonInstantiableClass () {
    //     throw new AssertionError();
    //}

    public static void printVariables () throws IllegalAccessException {

        for (Field field : NonInstantiableClass.class.getDeclaredFields()) {
            field.setAccessible(true);
            System.out.println(field.getName()
                    + " - " + field.getType()
                    + " - " + field.get(new NonInstantiableClass()));
        }
    }


    public static void main(String args[]) throws IllegalAccessException {
        NonInstantiableClass.printVariables();
    }
}

Are there a better approach to resolve this problem?

Thanks.





Aucun commentaire:

Enregistrer un commentaire