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.
-
`private` means that only the class which declares the field can use it. If you want to access it you need to define a public getter. Or use reflection. [Oracle](https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) – BackSlash Oct 03 '15 at 09:07
3 Answers
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.

- 20,430
- 4
- 39
- 67
-
for more info about the implementation -http://stackoverflow.com/a/1196207/3191896 – Jossef Harush Kadouri Oct 03 '15 at 09:07
-
can you briefly how I can do this via reflection, I'm going to do this as soon as possible and don't have enough time to study something. – Bootimar Oct 03 '15 at 09:07
-
would you please explain what are the badClassInstance and newValue in f.set method? @chiastic-security – Bootimar Oct 03 '15 at 11:21
Create getter and setter methods for the private fields.
example:
public void setName ( String name )
{
this.name = name;
}
public String getName ()
{
return this.name;
}

- 43
- 1
- 9
-
I want to use a combobox value in another class. I made a getter like this: public String getName () { Object selectedItem = cmbProductType.getSelectedItem(); String selectedItemStr = selectedItem.toString(); return selectedItemStr; } But when I use the field in my code in this way: String str = MainView.getName(); It says that “non-static method getName() cannot be referenced from a static context. – Bootimar Oct 03 '15 at 10:12
-
@Bootimar That information changes the problem. I strongly recommend adding it to the question, with the code properly formatted. Meanwhile, is it a duplicate of (http://stackoverflow.com/q/290884/1798593) – Patricia Shanahan Oct 03 '15 at 13:24
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.

- 226
- 3
- 6