Re: Anonymous class - I don't know how to...



kaja_love160@xxxxxxxxx wrote:

Example:

Object o = new Object() { public int anon = 20; };


The above statement creates an object of anonymous class and returns
a reference to it. But in order to use members declared in anonymous
class ( o.anon ), variable o would have to be of same type as
anonymous class. How do we make 'o' of same type, considering that
anonymous class has no name?

To re-enforce what Andreas said, this is a design issue, not a language issue. You must design your super-class so that you can access variables or other information from the anonymous class.

If you absolutely cannot, then here's the reflection example:

package anontest;
import java.lang.reflect.Field;

public class Main
{
public static void main(String[] args) throws IllegalAccessException
{
Object o = new Object() { public int anon = 20; };
printAnon( o );

}
static void printAnon( Object o ) throws IllegalAccessException
{
Class c = o.getClass();
Field fields[] = c.getDeclaredFields();
for( Field f : fields )
{
System.out.println( f.getName() + " = " + f.get( o ) );
}
}
}

Better to NOT use Object and just design an appropriate super-class however.
.