从字段中获取对象的实例,反射

时间:2016-03-18 08:05:43

标签: java reflection

我正在尝试修改位于我必须使用反射的地方的一些内容。问题是我希望将这些值(恰好是一个列表)作为Field然后更改它。当我得到该字段时,我得到字段的引用(副本)还是得到实际字段(这意味着如果我编辑它将从我从哪里开始改变)?

  //Get command map
    Field field = this.getServer().getClass().getDeclaredField("commandMap");
    field.setAccessible(true);
    CommandMap cmdmap = (CommandMap) field.get(this.getServer());
    //Get commands map
    Field f = cmdmap.getClass().getDeclaredField("knownCommands");
    f.setAccessible(true);
    Map<String, Command> kcmds = (Map<String, Command>) f.get(cmdmap);
    //Unregister all
    for(String s: cmdToUnregister)
    {
        for(String fp : kcmds.keySet())
        {
            if(s.equalsIgnoreCase(kcmds.get(fp).getName()))
            {
                kcmds.remove(fp);
            }
        }
    }
    //Re set fields
} catch (IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchFieldException ex) {
    Logger.getLogger(DivinityRealm.class.getName()).log(Level.SEVERE, null, ex);
}

我试过这个,它并没有刻意地工作。无论我不知道问题是我使用Reflection的方式还是我使用错误方法的事实?

1 个答案:

答案 0 :(得分:0)

当我发现kcmds实际上是实际列表的副本时,我的问题得到解决,必须使用反射重新设置它才能实际进行任何更改。另外,您只是获取副本并对其进行编辑以使其成为GC

相关问题