Over a million developers have joined DZone.

Reflection and the Missing Security Manager

· Java Zone

Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience, brought to you in partnership with JetBrains

Here’s an interesting trick that’s been around for a long time: Consider the Person class here, with password as a private data member.

public class Person {

private String name;
private String password;

public String getName() {
return name;

public boolean login(String password) {
if(this.password(equals(password)) {

The Java scope rules do not allow me to access or modify the password field that’s declared private. All the same, I could do it using reflection as shown below:

   Person person = db.queryPerson("alosh");
//System.out.println("password: "+person.password); -- won't compile

Field field = person.getClass().getField("password");
System.out.println("password: "+field.get(person));
field.set(person, "welcome");

It all boils down to this line of code.


All reflection access to an object (methods, fields, constructors) is through the interface AccessibleObject which lets the reflected object suppress the normal access controls. By setting the access flag, the reflected object is now open.
But the access flags are not flipped before it checks with the security manager. Reflection and SecurityManager together provides the power to control access dynamically.

Our little trick could then be attributed to the SecurityManager. Or like in this case, the lack of a SecurityManager.

By default the JVM does not have a SecurityManager available. A security manager could be installed either by passing the following option to the jvm


or by setting one in the code

System.setSecurityManager(new SecurityManager());

(Now the snippet mentioned in the beginning will not work.)

* SecurityManager is not enabled by default in the JVM.
* Majority of the JEE servers out there don’t run a SecurityManager unless asked for.
* Many applications would not run with SecurityManager in place.

Isn’t it against Java’s principle of ‘Secure by Default’?

From http://www.aloshbennett.in/weblog/2010/java/reflection-and-the-missing-security-manager/

Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}