AMDG
AMDG

Reputation: 1202

How could I access a private object from another class?

Is there some direct or indirect way to access a private object from another class?

Upvotes: 1

Views: 6042

Answers (3)

user3643581
user3643581

Reputation: 1

You can't access private object/variable from another class. A way to do that is to used getter and setter:

public class Sample{ private String name;

//setter
public void setName(String yourname){
    this.name = yourname;
}

//getter
public String getName(){
    return name;
}

}

class AccessPrivateVariable{ public static void main(String[] args){

    Sample sample = new Sample();

    /*call the setter from Sample class and pass value
    to its parameter*/
    sample.setName("Andrew");

    /*
    access the name "Andrew" by calling getter
    */
    System.out.println("Welcome " + sample.getName());
}   

}

Upvotes: -1

Scary Wombat
Scary Wombat

Reputation: 44854

The normal way is to create getter/setter methods for your private variables.

E.g.

private String myData;

public String getMyData () {
   return myData;
}

public void setMyData (String myData) {
    this.myData = myData;
}

If you do not want to do this then you can use reflection to access the private variables. See http://docs.oracle.com/javase/tutorial/reflect/

Upvotes: 1

Makoto
Makoto

Reputation: 106508

Well, reflection is really your only hope on this one. It'd be the only way you could inspect an object's fields without caring much for its visibility modifiers.

Entity entity = new Entity();
for(Field f : entity.getClass().getDeclaredFields()) {
    try {
        f.setAccessible(true);
        System.out.println(f.get(entity));
    } catch(IllegalAccessException e) {
        e.printStackTrace();
    }
}

But, I do want to strongly caveat you on resetting the accessibility of the field.

If you're running in a highly concurrent environment, and you disable the accessibility immediately after you're done, you will run into a case in which the accessibility is removed in one thread, as you're about to read it in another, which will lead to a giant, confusing mess.

At that point, the fact that you have visibility modifiers becomes moot, and you would want to just use a part-and-parcel getter instead (or have the field be public, which makes many feel weird about).

Upvotes: 4

Related Questions