How to read the value of a private field from a different class in Java?
In order to access private fields, you need to get them from the class's declared fields and then make them accessible:
Field f = obj.getClass().getDeclaredField("stuffIWant"); //NoSuchFieldException
f.setAccessible(true);
Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException
EDIT: as has been commented by aperkins, both accessing the field, setting it as accessible and retrieving the value can throw Exception
s, although the only checked exceptions you need to be mindful of are commented above.
The NoSuchFieldException
would be thrown if you asked for a field by a name which did not correspond to a declared field.
obj.getClass().getDeclaredField("misspelled"); //will throw NoSuchFieldException
The IllegalAccessException
would be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out the f.setAccessible(true)
line.
The RuntimeException
s which may be thrown are either SecurityException
s (if the JVM's SecurityManager
will not allow you to change a field's accessibility), or IllegalArgumentException
s, if you try and access the field on an object not of the field's class's type:
f.get("BOB"); //will throw IllegalArgumentException, as String is of the wrong type
How to access a value of a private instance variable from a different class?
To make the state of the managed bean accessible
, you need to add setter
and getter
methods for that state.
Once the setter and getter (accessor) methods have been added, you can update and access the value of the private
instance. The code should look like the following example:
public class AccessorExample {
private String attribute;
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
}
Letting access the information inside the private
instance from outside of the class, only if they ask through a provided mechanism we will call method. The mechanisms for asking an object to reveal information about itself we can call the getter
method (e.g. accessorExample.getAttribute();
).
How do you access a private field from another class without a getter?
You can use the Apcache commons FieldUtils
FieldUtils.readField(object, myfield, true);
or else you can use the Reflection as is described and answered in the linked duplicate. So you can set the setAccessible(true)
before invoking your method.
m = object.getClass().getDeclaredMethod(mymethod);
m.setAccessible(true);
m.invoke(object);
Accessing private variable from another class in Java
Since "addStudentToRoster" is defined inside the Course class, you need to create an instance of that class and modify the problem line of code to be something like:
Course comp101 = new Course(1, "comp101", 80, 2.0);
comp101.addStudentToRoster(newStudent);
Java: Accessing private fields directly from another instance of the same class
No, it's not. The reason that private variables and methods are not accessable from other classes is to allow you to change the internals of your class without having to change all the code that uses the class (that and to prevent the user of your class from e.g. setting a variable to a value that it's never supposed to have).
If you use private variables of other objects that doesn't hurt anything, because if you'd restructure your class's internals, you'd have to change the code inside the class anyway.
Related Topics
Assigning Variables With Dynamic Names in Java
Why Is 128==128 False But 127==127 Is True When Comparing Integer Wrappers in Java
How to Create a Java String from the Contents of a File
Loop Doesn't See Value Changed by Other Thread Without a Print Statement
Convert a String Representation of a Hex Dump to a Byte Array Using Java
What's Wrong With Java Date & Time API
How to Stop Repeated Keypressed()/Keyreleased() Events in Swing
Why Don't Java Generics Support Primitive Types
How to Clone Arraylist and Also Clone Its Contents
How to Get the Current Working Directory in Java
Why Is a Concurrentmodificationexception Thrown and How to Debug It
Why Is Java Vector (And Stack) Class Considered Obsolete or Deprecated
How to Read All Files in a Folder from Java
How to Count the Number of Occurrences of a Char in a String
Floating Point Arithmetic Not Producing Exact Results
Convert Inputstream to Byte Array in Java
Error Java.Lang.Outofmemoryerror: Gc Overhead Limit Exceeded