HashMap的代理NullPointerException

时间:2018-11-13 12:51:47

标签: java proxy invocationhandler

我正在尝试在WebApp和磁盘上的存储之间建立代理。我知道对于WebApp来说一切正常,甚至可以将内容保存到磁盘上,所以我知道调用了我InvocationHandler上的Invoke方法,但是代理本身似乎为Null,因此WebApp上的任何内容都没有更新。

代理的创建:

public class Storage {

public static final Storage INSTANCE = new Storage();

private Storage() {

}

//private final Map<String, Note> tmpStorage = new HashMap<>();

public Map<String, Note> getStorageForUser(Credentials credentials) {
    String location = "./storage/"+credentials.getUsername();
    return (Map<String, Note>) Proxy.newProxyInstance(
            Map.class.getClassLoader(),
            new Class<?>[]{Map.class},
            new FileStorageMap(location, new HashMap<>()));
    //return tmpStorage;
}

}

InvocationHandler:

    @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (method.getName() == "post" || method.getName() == "put"){
        FileUtils.writeStringToFile(new File(folder.getPath()+"/"+args[0]), (new NoteToJson((Note)args[1])).getJson().toString(), "UTF-8");
    }
    else{
        new File(folder.getPath()+"/"+args[0]).delete();
    }
    return method.invoke(proxiedMap, args);
}

我已经检查并在创建名为“ FileStorageMap”的InvocationHandler时,folder和proxiedMap是数据字段,它们都不为Null,它们都正确填写。但是对于代理本身,它返回NullPointerException。谁能告诉我为什么?

1 个答案:

答案 0 :(得分:0)

该错误在于以下事实:方法名称错误,而else语句要使用的东西超出了我的预期。代理本身并不是真正的问题。