简体   繁体   中英

return “constant” value from method java

I'm not quite sure if this is possible so that's why I ask you guys. I want to write a method that knows if it has been visited before and if it has return the same value it has lasttime it were visited. I can't use fields/instance varibles for this.

This is want I want to do, without the instance variable foo:

private FooObject foo = null;
public int setFoo(FooObject in)
{
    if(foo == null)
        foo = in;

    return foo.getX();
}

Could this be done?

that knows if it has been visited before

Knowledge of what happened before requires memory, aka state . Therefore you will need something to store that knowledge; you can't avoid it.

I agree with @Oli Charlesworth, you cannot do this without state. But using a field to save state is just one of many options. You could, for instance, save the state as a system property using System.setProperty() and System.getProperty(), or save the state to a file. You could even save the state to a database.

Without using an instance variable? no, it can't be done. You need a way for the method to "remember" something between calls - a local variable won't work, it has to be something that "lives" outside a method call. And that's what an instance variable is for: saving state, visible from all instance methods.

You can use a cache. Read from cache for looking for the input. If the input is already in cache, then return the value from cache. If don't, put the entry in cache and return the new calculated value.

CacheManager singletonManager = CacheManager.create();
Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
manager.addCache(memoryOnlyCache);
Cache cache = singletonManager.getCache("testCache");

Put new entry

Element element = new Element("key1", "value1");
cache.put(element);

Looking for in chache:

Element element = cache.get("key1");
Object value = element.getObjectValue();

For remove:

cache.remove("key1");

You can persist this to disk.

For more information, see in http://ehcache.org/

You could use the Preferences API . That allows you to store memory across application loads though, so if you want it to be restarted each time you load, you'll need to set a shutdown hook to clear the value from the Preferences API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM