Re: Anonymous class - I don't know how to...
- From: Mark Space <markspace@xxxxxxxxxxxxxx>
- Date: Thu, 28 Jun 2007 21:19:39 GMT
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.
.
- Follow-Ups:
- Re: Anonymous class - I don't know how to...
- From: Patricia Shanahan
- Re: Anonymous class - I don't know how to...
- From: Tom Hawtin
- Re: Anonymous class - I don't know how to...
- References:
- Anonymous class - I don't know how to...
- From: kaja_love160
- Anonymous class - I don't know how to...
- Prev by Date: Applet Sandbox Rules
- Next by Date: Re: Anonymous class - I don't know how to...
- Previous by thread: Re: Anonymous class - I don't know how to...
- Next by thread: Re: Anonymous class - I don't know how to...
- Index(es):