I want to access an object which is created in some method of a class, from other method of same class.
public class SomeClass implements SomeInterface{
public void someMethod(int a, int b){ //Implemented method
{
SomeOtherClass soc = new SomeOtherClass();
//some setting process
}
public int someOtherMethod(){
SomeOtherClass newSOC = soc;//Here, can i access the soc object created in "someMethod"
}
}
Actually, i want to set some data in the object and retrieve the data from different method. Is that possible!!!
Given the constraints that the object instanced of
SomeClassis used for multiple requests (e.g. where one request are both invocations of the two methods) and that they must be encapsulated properly, e.g. in a multi user system, you need to have a state object where you can transfer the results of the first method to the second method.Since the object instance of
SomeClassis considered a shared class in this scenario, you need something else.Two ways:
Both options require to change the implementation of the first method.
If you cannot, for any reason, change the implementation of the first method, the answer to your question is: No, you cannot access the
socobject from with the second method, as the first object is out of scope, e.g. it may already be garbage collected and gone.For the latter, you may want to use a
ThreadLocal. This comes in handy if you know that a request (for example a HTTP Servlet Request) is unique for a user or a request and so you can share the information/state object in aThreadLocalbetween the invocation of the first method and the second method. If you object instance ofSomeClassis reused by different Threads, then you need to take care of properly cleaning up!