Recent Posts
Archives

PostHeaderIcon How to access non-visible fields in Java?

How to access a non-acccessible field (either protected, package-protected or private) of an object in Java?

For instance, you would like to access the field threads of ThreadGroup:

[java]ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
final Field privateThreadsField;
privateThreadsField = ThreadGroup.class.getDeclaredField("threads");
privateThreadsField.setAccessible(true);
threads = (Thread[]) privateThreadsField.get(threadGroup);[/java]

Leave a Reply