English 中文(简体)
Getting package-level access to a field from outside the package?
原标题:
  • 时间:2009-11-12 12:40:44
  •  标签:
  • java
  • field

I m using an API that has an abstract class that I wish to extend (in my concrete class) in order to take advantage of some methods within the parent. Unfortunately, the programmer of that API class decided with one field in particular to give it package-level access with no public setter. The field value is instead set within a method. Is there a common "bridge pattern" so that I can get/set that field appropriately? This is not only important for my functionality, but for testing as well (since I will need to mock out the value that is set in that field in my test). Thanks!

最佳回答

Some possibilities:

  • Obtain and modify the source code for "the API".

  • Write a class in the same package to sneak access to and expose the field you need.

  • Write a wrapper around the API s class providing access to that field with any changed semantics you like.

  • Use reflection to break the access protection on the API s class.

问题回答

You are going to have to use reflection in order to set the field. In order to set the field, you d call setAccessible on it. I haven t tested this but something like the following should work:

ClassWithProtectedField o = new ClassWithProtectedField();
Class c = o.getClass();
java.lang.reflect.Field protectedField = c.getField("protectedField");
protectedField.setAccessible(true);
protectedField.set(o, someValue);

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Field.html

If you are able, you could create a subclass of the API class within the original package and expose the field publicly. If you cannot do this then you could potentially use reflection to modify the field s value, assuming that your SecurityManager is configured to allow it - but this feels like a bit of a code smell.

If you have control over the SecurityManager or there is non in place, you can use Reflection to make the field accessible and then change its value.

Example code:

import java.lang.reflect.Field;

public class ModifyProtectedFieldSample {

    public static void setProtectedField(final Object targetClass,
                                     final String fieldName,
                                     final Object value) {
    try {
        final Field field = targetClass.getClass().getDeclaredField(fieldName);
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }

        field.set(targetClass, value);
    } catch (NoSuchFieldException e) {
        System.out.println("NoSuchFieldException " + e);
    } catch (SecurityException e) {
        System.out.println("SecurityException"+ e);
    } catch (IllegalAccessException e) {
        System.out.println("IllegalAccessException"+ e);
    }
  }

  public static void main(final String[] args) {
    setProtectedField(String.class, "someFieldName", Boolean.FALSE);
  }
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签