简体   繁体   中英

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.

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.

Create getter and setter methods for the private fields.

example:

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

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

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.

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