Reputation: 9794
I am using .getDeclaredClasses() method to retrieve all the classes that have been defined in object. However, I am not able to retrieve anonymous classes defined in the class. Here is the code sample that I am testing:
public class TempCodes
{
public static void main(String[] args)
{
Ball b = new Ball()
{
public void hit()
{
System.out.println("You hit it!");
}
};
b.hit();
}
interface Ball {
void hit();
}
}
and this is what my code does:
memClass = className.getDeclaredClasses();
if (memClass .length > 0)
{
for (int index = 0 ; index < memClass .length ; index++)
{
System.out.println("\t\t\t" + memClass [index]);
}
}
Can anyone help me understand how to retrieve the anonymous class?
Regards, darkie
Upvotes: 0
Views: 357
Reputation: 1108632
With little help of the classpath:
final Class<?> cls = TempCodes.class;
String[] names = new File(cls.getResource("").toURI()).list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(cls.getSimpleName());
}
});
for (String name : names) {
System.out.println(name);
}
Result:
TempCodes$1.class TempCodes$Ball.class TempCodes.class
You've to filter the desired information out yourself.
Disclaimer: doesn't work well with JAR files, but the hint is clear enough: it's not possible with reflection. I would question the need for this and rethink the design or approach. Here are some topics of interest: Java reflection: How can I retrieve anonymous inner classes? and Accessing inner anonymous class members.
Upvotes: 1