Reflective access to a static variable in a Java class

They gave me no choice but to access a set of classes that I cannot change, with this structure through reflection. However, using the method shown in the main method below throws a NullPointerException. A null pointer is a β€œtable” in the constructor when f1.get (null) is called.

I cannot create an instance of classes in advance, because the only constructor is the one that is shown, which is private. Therefore, I cannot explicitly specify the table.

Does anyone know how to reflectively call Legacy.A?

public class Legacy {   
    public static final Legacy A = new Legacy("A");
    public static final Legacy B = new Legacy("B");

    private String type0;
    private static Map<String, Legacy> table = new HashMap<String, Legacy>();

    private Legacy(String id) {
        type0 = id;
        table.put(type0, this);
    }

    public static void main(String[] args) throws Exception {
        Field f1 = Legacy.class.getDeclaredField("A");
        Object o = f1.get(null);    
    }
}

In front of "Reflection == BAD !!!"

+3
source share
3

, .

, . .

+7

, :

public class Legacy {   
        static {
          table = new HashMap<String, Legacy>();
          A = new Legacy("A");
          B = new Legacy("B");
        }

        public static final Legacy A;
        public static final Legacy B;

        private String type0;
        private static Map<String, Legacy> table;

        private Legacy(String id) {
                type0 = id;
                table.put(type0, this);
        }

    public static void main(String[] args) throws Exception {
                Field f1 = Legacy.class.getDeclaredField("A");
                Object o = f1.get(null);        
        }
}

, (- , - ), .

+4

I tried this because I could not understand what was wrong with your example. It worked if I reordered ads:

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class Legacy {
    private String type0;
    private static Map< String, Legacy > table = new HashMap< String, Legacy >();

    private Legacy( String id ) {
        type0 = id;
        table.put( type0, this );
    }
    public static final Legacy A = new Legacy( "A" );
    public static final Legacy B = new Legacy( "B" );

    public static void main( String[] args ) throws Exception {
        Field f1 = Legacy.class.getDeclaredField( "A" );
        Object o = f1.get( null );
    }
}

Static declarations need a constructor (previous).

0
source

Source: https://habr.com/ru/post/1714807/


All Articles