获取带有反射的哈希映射表

huangapple go评论78阅读模式
英文:

Get HashMap with Reflection

问题

public class First {
    public final static Map<String, String> MAP = new HashMap<>();
    static {
        MAP.put("A", "1");
        MAP.put("B", "2");
    }
}

public class Second {
    public static void main(String[] args) {
        try {
            Class<?> clazz = Class.forName("First");
            Field field = clazz.getDeclaredField("MAP");
            field.setAccessible(true);
            Map<String, String> newMap = (Map<String, String>) field.get(null);
            // Now you can use the 'newMap' instance to access the values in the MAP.
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
英文:
public class First {
    public final static Map&lt;String, String&gt; MAP = new HashMap&lt;&gt;();
    static {
        MAP.put(&quot;A&quot;, &quot;1&quot;);
        MAP.put(&quot;B&quot;, &quot;2&quot;);
    }
}

public class Second {
    public static void main(String[] args) {
        Class&lt;?&gt; clazz = Class.forName(&quot;First&quot;);
        Field field = clazz.getField(&quot;MAP&quot;);
        Map&lt;String, String&gt; newMap = (HashMap&lt;String, String&gt;) field.get(null); // Obviously doesn&#39;t work
    }
}

Pretty much it. I have no trouble getting for example values of String variables, but I'm stuck with this one. Tryed to google it, failed. Also, if possible I'd like to get this Map without instantiating its class.

答案1

得分: 3

你唯一缺少的是处理以下情况的异常:

  • Class.forName("First");
  • clazz.getField("MAP");
  • field.get(null);

以下代码从First类中获取静态映射字段。在此,我只是在主方法中抛出/传播异常,但你应该在try/catch块中适当处理异常。

class First {
  public final static Map<String, String> MAP = new HashMap<>();
  static {
    MAP.put("A", "1");
    MAP.put("B", "2");
  }
}

public class Second {
  public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException,
      ClassNotFoundException, NoSuchFieldException, SecurityException {
    Class<?> clazz = Class.forName("First");
    Field field = clazz.getField("MAP");
    Map<String, String> newMap = (HashMap<String, String>) field.get(null); // 显然不起作用
    System.out.println(newMap); // 输出 {A=1, B=2}
  }
}
英文:

The only thing you are missing is to handle the exceptions for:

  • Class.forName("First");
  • clazz.getField("MAP");
  • field.get(null);

The code below get the static map field from First class. Here I'm just throwing/propagating the exceptions in the main method but you should handle the exceptions in a try/catch block accordingly.

class First {
  public final static Map&lt;String, String&gt; MAP = new HashMap&lt;&gt;();
  static {
    MAP.put(&quot;A&quot;, &quot;1&quot;);
    MAP.put(&quot;B&quot;, &quot;2&quot;);
  }
}


public class Second {
  public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException,
      ClassNotFoundException, NoSuchFieldException, SecurityException {
    Class&lt;?&gt; clazz = Class.forName(&quot;First&quot;);
    Field field = clazz.getField(&quot;MAP&quot;);
    Map&lt;String, String&gt; newMap = (HashMap&lt;String, String&gt;) field.get(null); // Obviously doesn&#39;t work
    System.out.println(newMap); //Prints {A=1, B=2}
  }
}

答案2

得分: 1

以下是同一个示例,使用非静态类:

package at.noe.szb;
import static org.junit.Assert.assertEquals;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;

public class ReflectionTest {
    private class First {
        public Map<String, String> MAP = new HashMap<>();
        First(){
            MAP.put("A", "1");
            MAP.put("B", "2");
        }
    }
    @Test
    public void testMap() throws Exception {
        Class<?> clazz = Class.forName("at.noe.szb.First");
        Field field = clazz.getField("MAP");
        Map<String, String> newMap = (HashMap<String, String>) field.get(clazz);
        assertEquals("{A=1, B=2}", newMap.toString());
    }
}
英文:

Here the same example with a non static class:

package at.noe.szb;
import static org.junit.Assert.assertEquals;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;

public class ReflectionTest {
    private class First {
        public Map&lt;String, String&gt; MAP = new HashMap&lt;&gt;();
        First(){
            MAP.put(&quot;A&quot;, &quot;1&quot;);
            MAP.put(&quot;B&quot;, &quot;2&quot;);
        }
    }
    @Test
    public void testMap() throws Exception {
        Class&lt;?&gt; clazz = Class.forName(&quot;at.noe.szb.First&quot;);
        Field field = clazz.getField(&quot;MAP&quot;);
        Map&lt;String, String&gt; newMap = (HashMap&lt;String, String&gt;) field.get(clazz);
        assertEquals(&quot;{A=1, B=2}&quot;, newMap.toString());
    }
}

huangapple
  • 本文由 发表于 2020年8月27日 21:49:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63617459.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定