Bootimar
Bootimar

Reputation: 3

How to access a non-static private field in java?

I have a non-static private field in a package and want to access it from another package but I don't know how to do that. I searched but I didn't find anything useful and other questions in this site weren't exacatly my question.

Upvotes: 0

Views: 546

Answers (3)

A.jiji
A.jiji

Reputation: 226

You should import the package where that non-static private field is. If you want to access this field from subclass which is in a different package you can change "private" modifier to "protected", this will allow all packages in the same project access this field through inheritance.

Upvotes: 0

thechamp
thechamp

Reputation: 53

Create getter and setter methods for the private fields.

example:

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

public String getName ()
{
     return this.name;
}

Upvotes: 2

chiastic-security
chiastic-security

Reputation: 20520

The only way you can do this is via reflection. But it's a hack. You really ought to be finding another way round it.

If you need to do it, then it suggests that the other package has a badly designed structure. If the class you're trying to manipulate is one of your own, you should look at changing that code.

If you really need to do it and you can't change the other class, you do it with something like this:

Field f = BadClass.class.getDeclaredField("privateField");
f.setAccessible(true);
f.set(badClassInstance, newValue);

Probably the best places to start are a tutorial on reflection, and the setAccessible method.

Upvotes: 3

Related Questions