Sunday, September 24, 2006

Tip #2: How to access the private variables outside the class in java?

Is that possible?

Yes, it is. Have you ever heard of ‘Java Reflection API’?. If no, then this brief intro can help. Java Reflection API: has set of classes and methods to access the runtime behavior and memory foot print of classes and objects”

Using the reflection API, you can access (any) instance member variable of an object. Yet, you can do a lot more with that.

Don't you thing this is a loop hole in Java? Breaking the integrity of Oops?

Not in that way. This API actually meant for helping people tracing the memory foot print and for developing applications like ‘Java Debugger’, ‘Java Profiler’, ‘Java Application Monitor’ and the likes. Usually, other applications programmers are advised not to use this API unnecessarily.

The following simple example demonstrates how to access the private variable of an object outside the class (using Reflection API):

(This example is referred from javareference.com)

java.lang.reflect.*;

class Example {

private int x = 10; // means not available to outside the class
public int y = 10; // accessible from anywhere.

}

public class ReflectionDemo

{
public static void main(String[] args) throws Exception {

Example e = new Example();
Class ref = e.getClass(); //will return ‘Example’ – right?
Field f = ref.getDeclaredField("x"); // watch here! :)
f.setAccessible(true); // Now the ‘x’ is accessible!
Object obj = f.get(e);
int val=((Integer) obj).intValue();
System.out.println("Private var X is = " + val);

}
}


That’s it!

If you want to know more about Reflection API, spend some minutes at Sun sites/ Tutorial.

Answer for Tip #1

Here comes the answer for the question asked in last tip (Tip #1 Java Memory Issues) : To run the program successfully, you have to increase the memory by using JVM command line options –Xmx and –Xms, like

$java –Xms20m –Xmx120m Memory

The -Xms20m options instructs the JVM to set the initial heap size to be 20 MB and the –Xmx120m options instructs the JVM to set the Maximum heap size to be 120 MB. (If this doesn’t work for your machine, you can try changing the numbers).

3 comments:

prabs said...

mani is it a only way of acessing the private members? i guess we can access in other ways also right??...

Manivannan P said...

I know only this way, prab. If you know other way, Please post!

prabs said...

mani.. i donnu... :(