Please don't post an answer saying "you shouldn't do this." I don't plan to use this in production code, but only for some hacking fun.
In answering this question, I wanted to run some arbitrary unsafe Java code for fun. The code in question involves finding just the leaf nodes of a Java TreeMap
.
Running the below code results in
Exception in thread "main" java.lang.SecurityException: Prohibited package name: java.util
According to this question, I can use System.setSecurityManager(null)
to get around most of these restrictions. But I can't do this because the error pops up as my class is loaded.
I'm already aware that I can do everything I want to using reflection after disabling the security manager. But that would make the code much uglier. How do the core Java developers write their unit tests, for example, if they can't package things in java.util
?
I also tried -Djava.security.manager=...
but this causes a JVM initialization error when I set it to null
, and I'm not sure what else I can set it to. Any ideas?
package java.util;
import java.util.TreeMap.Entry;
public class TreeMapHax {
static <K,V> List<Entry<K, V>> getLeafEntries(TreeMap<K, V> map) {
Entry<K, V> root = map.getFirstEntry();
while( root.parent != null ) root = root.parent;
List<Entry<K,V>> l = new LinkedList<Entry<K,V>>();
visitInOrderLeaves(root, l);
return l;
}
static <K,V> void visitInOrderLeaves(Entry<K, V> node, List<Entry<K, V>> accum) {
if( node.left != null ) visitInOrderLeaves(node.left, accum);
if( node.left == null && node.right == null ) accum.add(node);
if( node.right != null ) visitInOrderLeaves(node.right, accum);
}
public static void main(String[] args) {
TreeMap<String, Integer> map = new TreeMap<String, Integer>();
for( int i = 0; i < 10; i++ )
map.put(Integer.toString(i), i);
System.out.println(getLeafEntries(map));
}
}