I have following classses
Hello.java
package speak.hello;
import java.util.Map;
import speak.hi.CustomMap;
import speak.hi.Hi;
public cla
I don't recommend to use non-API classes as they might change in any future version and can break your code.
How did you find out about this class? Is it an Open Source library?
Try to contact the authors of the library, tell them your use case and find a way with them to offer a public API. If it's an open source library you could help them by providing a patch.
Is there any other way to do this ? Using reflection perhaps ?
Yes. Reflection can be used to bypass the Java access rules, if your application has full privilege.
For instance, to access a private
field of an object from a different class, you need to:
Class
object.Class.getDeclaredField(...)
method to get a Field
object for the field.Field.setAccessible(true)
to turn off the access check.Class.getField(object, Field)
to get the field's value (or boxed value if it is a primitive type).If the class itself is not accessible, you need to make sure that you don't refer to the classes identifier in your source code ... 'cos that will result in a compilation error. Instead, assign its reference to (say) variable of type Object
or of some other visible supertype, and perform more specific operations on the instance reflectively.
As you might imagine, this is tedious and error prone. You'd be advised to find a better way, like:
(Generally speaking, if you have to break open an abstraction then something is wrong with either the abstraction itself or the way you are using it.)
Finally, I should add that untrusted code is (should be) run in a security sandbox that blocks the use of the key reflective operations.
I think by default the class will be "default" (package private, you can say), NOT "private". So it can be accessed with in the same package.
Moreover, you CANNOT make any *top level class Private in Java.
And if you want make a class default and still be able to access it in other package then what will be the purpose of having access specifiers (modifiers) ??
you either need to make class public or move to the same package.
Following method Invokes default
scoped class method using reflection
public void discardMap() {
//CustomMap map = (CustomMap) hi.getMap();
//map.discard();
try {
Object o =hi.getClass().getMethod("getMap").invoke(hi);
Method m = o.getClass().getMethod("discard");
m.setAccessible(true);
m.invoke(o);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}