krosenvold
krosenvold

Reputation: 77171

Library that subverts java access control and lets me access private member variables?

Can anoyne recommend a good library that will let me easily read/write private member fields of a class? I was looking through apache commons, but couldnt see it. I must be getting blind ?

Edit: Asking questions on the border of legalities always give these questions of "why"? I am writing several javarebel plugins for hotswapping classes. Accessing private variables is only step 1, I might even have to replace implementations of some methods.

Upvotes: 1

Views: 549

Answers (3)

sakana
sakana

Reputation: 4481

In most of the cases java reflection solves the problem:

Example:

public class Foo {

    /**
     * Gets the name Field.
     * 
     * @return the name
     */
    public final String getName() {
        return name;
    }

    /**
     * Sets the name Field with the name input value.
     * 
     * @param name the name to set
     */
    public final void setName(String name) {
        this.name = name;
    }

    private String name;

}

Now the Reflection Code:

import java.lang.reflect.Field;
....

Foo foo = new Foo();
foo.setName("old Name");
String fieldName = "name";
Class class1 = Foo.class;

try {

    System.out.println(foo.getName());

    Field field = class1.getDeclaredField(fieldName);

    field.setAccessible(true);

    field.set(foo, "My New Name");

    System.out.println(foo.getName());

} catch (NoSuchFieldException e) {
    System.out.println("FieldNotFound: " + e);
} catch (IllegalAccessException e) {
    System.out.println("Ilegal Access: " + e);
}

UPDATE:

It's worth mentioning that this approach can be thwarted by a SecurityManager. – Dan Dyer

Upvotes: 7

Matthew Brubaker
Matthew Brubaker

Reputation: 3117

Without knowing why you want that level of access, I can only wonder what you could need that level of access for. Private members are private for a reason. They are not intended to be accessed from outside the class and could result in undocumented behavior.

That said, you can get access to most things through the java.lang.reflect package.

In my opinion, you should examine why you think you need that level of access and see if you could be doing something differently to not need it.

Upvotes: 3

Ken Gentle
Ken Gentle

Reputation: 13357

The java.lang.reflect package classes and methods allow this access, within certain limits.

See java.lang.reflect

Upvotes: 1

Related Questions