There is no linguistic support to do what you ask.
You can reflect type elements at runtime using reflection (e.g. Class.getDeclaredFields() to get a Field array), but depending on what you are trying to do, this might not be the best solution.
see also
Related Questions
- What is reflection and why is it useful?
- Java Reflection: why is it so bad?
- How can reflection lead to code smells?
- Reset properties of java objects
Example
Here is a simple example to show only what reflections can do.
import java.lang.reflect.*; public class DumpFields { public static void main(String[] args) { inspect(String.class); } static <T> void inspect(Class<T> klazz) { Field[] fields = klazz.getDeclaredFields(); System.out.printf("%d fields:%n", fields.length); for (Field field : fields) { System.out.printf("%s %s %s%n", Modifier.toString(field.getModifiers()), field.getType().getSimpleName(), field.getName() ); } } }
The snippet above uses reflection to validate all declared fields of class String ; he produces the following conclusion:
7 fields: private final char[] value private final int offset private final int count private int hash private static final long serialVersionUID private static final ObjectStreamField[] serialPersistentFields public static final Comparator CASE_INSENSITIVE_ORDER
Effective Java 2nd Edition, paragraph 53: Preferred interfaces for reflection
These are excerpts from the book:
Given the Class object, you can get Constructor , Method and Field instances representing the constructors, methods, and fields of the class. [They] allow you to reflexively manipulate their basic counterparts. This power, however, comes at a price:
- You are losing all the benefits of compile time checking.
- The code required to provide reflective access is inconvenient and detailed.
- Performance.
Typically, objects should not pay attention to regular applications at run time.
There are several complex applications that require reflection. Examples include [... omitted specifically ...] If you have any doubts as to whether your application falls into one of these categories, this probably does not.
polygenelubricants Jul 26 '10 at 10:28 2010-07-26 10:28
source share