Reputation: 20069
Is there a simple way to add my own classes to java.lang (in the context of a desktop application, not applet/servlet). The idea is to get access to some methods that have been stupidly declared package private (such as Integer.getChars(...), and I don't want to copy all that code).
Simply declaring a class in the java.lang package triggers a SecurityException when my class loads.
I'm aware I could unzip the rt.jar and add my class there, but I'm looking for a method that doesn't require modifications to the installed JRE.
EDIT: I forgot to mention that I want direct access to the methods, not roundabout detour access methods like reflection. the goal is to make a a call like Integer.getChars(int, index, chars) not only compile but also execute normally at runtime.
Upvotes: 2
Views: 387
Reputation: 20069
Its possible to add classes to packages protected by the boot class-loader's SecurityManager by using the non-standard "-Xbootclasspath/p:" parameter (Oracle VM). Classes added in this manner are "trusted", and since they are located before rt.jar in terms of search order, this can also be used to replace classes defined in the JRE.
Upvotes: 3
Reputation: 17622
You can do it using Java Reflections
Class<Integer> clazz = Integer.class;
Method m = clazz.getDeclaredMethod("getChars", int.class, int.class, char[].class);
m.setAccessible(true);
m.invoke(new Integer(1), 0, 0, new char[] {'1'});
// OR
//m.invoke(null , 0, 0, new char[] {'1'}); since getChars method is static and doesn't require an instance
Upvotes: 3