Reflection is the ability of software to analyze itself.
The following application illustrates a simple use of the Java reflection capabilities.
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Main {
public static void main(String args[]) {
try {
Class c = Class.forName("java.awt.Dimension");
System.out.println("Constructors:");
Constructor constructors[] = c.getConstructors();
for (int i = 0; i < constructors.length; i++) {
System.out.println(" " + constructors[i]);
}
System.out.println("Fields:");
Field fields[] = c.getFields();
for (int i = 0; i < fields.length; i++) {
System.out.println(" " + fields[i]);
}
System.out.println("Methods:");
Method methods[] = c.getMethods();
for (int i = 0; i < methods.length; i++) {
System.out.println(" " + methods[i]);
}
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
Here is the output from this program:
Constructors:
public java.awt.Dimension(java.awt.Dimension)
public java.awt.Dimension(int,int)
public java.awt.Dimension()
Fields:
public int java.awt.Dimension.width
public int java.awt.Dimension.height
Methods:
public int java.awt.Dimension.hashCode()
public boolean java.awt.Dimension.equals(java.lang.Object)
public java.lang.String java.awt.Dimension.toString()
public java.awt.Dimension java.awt.Dimension.getSize()
public void java.awt.Dimension.setSize(int,int)
public void java.awt.Dimension.setSize(double,double)
public void java.awt.Dimension.setSize(java.awt.Dimension)
public double java.awt.Dimension.getHeight()
public double java.awt.Dimension.getWidth()
public java.lang.Object java.awt.geom.Dimension2D.clone()
public void java.awt.geom.Dimension2D.setSize(java.awt.geom.Dimension2D)
public final native java.lang.Class java.lang.Object.getClass()
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
Classes Defined in java.lang.reflect package
Class | Primary Function |
---|---|
AccessibleObject | Allows you to bypass the default access control checks. |
Array | Allows you to dynamically create and manipulate arrays. |
Constructor | Provides information about a constructor. |
Field | Provides information about a field. |
Method | Provides information about a method. |
Modifier | Provides information about class and member access modifiers. |
Proxy | Supports dynamic proxy classes. |
ReflectPermission | Allows reflection of private or protected members of a class. |
java2s.com | Contact Us | Privacy Policy |
Copyright 2009 - 12 Demo Source and Support. All rights reserved. |
All other trademarks are property of their respective owners. |