Cheney
asked on
Accessing private class variables
Hello.
Im having trouble finding a solution for the following problem:
I have a class A that contains a private variable:
class A
{
private double variable;
}
I need to access variable (both get and set) from another class, WITHOUT adding get and set methods to the class. I tried to use a second, inner, class as it too whould have access to the variable, however this was daft as you cannot instante inner classes of one class from another...
I need a way to access variable, whether it be through a second class or some kind of hack.
Thanks in advance for your assistance.
Rick.
Im having trouble finding a solution for the following problem:
I have a class A that contains a private variable:
class A
{
private double variable;
}
I need to access variable (both get and set) from another class, WITHOUT adding get and set methods to the class. I tried to use a second, inner, class as it too whould have access to the variable, however this was daft as you cannot instante inner classes of one class from another...
I need a way to access variable, whether it be through a second class or some kind of hack.
Thanks in advance for your assistance.
Rick.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
how about using protected ????
> how about using protected ????
only good if you're extending the class
only good if you're extending the class
import java.lang.reflect.*;
Here's an example that reads all member vars of a class including private.
public class ReadPrivateFields
{
public static void main(String[] args) throws Exception
{
Class c = Class.forName(args[0]);
Object o = c.newInstance();
Field[] fields = c.getDeclaredFields();
for (int i = 0; i < fields.length; i++)
{
String key = fields[i].getName();
fields[i].setAccessible(tr ue);
System.out.println(field + " -value- " + fields[i].get(o));
}
}
}
Here's an example that reads all member vars of a class including private.
public class ReadPrivateFields
{
public static void main(String[] args) throws Exception
{
Class c = Class.forName(args[0]);
Object o = c.newInstance();
Field[] fields = c.getDeclaredFields();
for (int i = 0; i < fields.length; i++)
{
String key = fields[i].getName();
fields[i].setAccessible(tr
System.out.println(field + " -value- " + fields[i].get(o));
}
}
}
>> how about using protected ????
>only good if you're extending the class
... or under the same package.
>only good if you're extending the class
... or under the same package.
Nice code there objects.. i'm keeping it for future reference =)
~ Objects the Visible Difference, nice slogan hehe
~ Objects the Visible Difference, nice slogan hehe
> Objects the Visible Difference, nice slogan hehe
A marketing mate came up with that for me, I'll pass on your approval to him :)
A marketing mate came up with that for me, I'll pass on your approval to him :)
ASKER