public class Car { private String maker; public Car(String c) { maker = c; } public String toString() { return "Car: "+maker; } }
import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Constructor; public class C { public static void main(String args[]) throws ClassNotFoundException { //create class objects Class c1 = Class.forName("java.lang.String"); Car car = new Car("Buick"); Class c2 = Car.class; Class c3 = car.getClass(); //toString System.out.println(c1); System.out.println(c2); System.out.println(c3); //isInstance System.out.println(c1.isInstance("Hello World!"));//true System.out.println(c2.isInstance(new Car("Buick")));//true //isInterface Class c4 = Class.forName("java.lang.Runnable");//true System.out.println(c4.isInterface()); //isPrimitive int i = 10; Integer i2 = new Integer(100); System.out.println((int.class).isPrimitive());//true System.out.println(i2.getClass().isPrimitive());//false //isArray int array[] = new int[10]; System.out.println(array.getClass().isArray());//true //getName System.out.println(c1.getName()); //getSuperclass Class c5 = c1.getSuperclass(); System.out.println(c5); //getPackage System.out.println(c1.getPackage()); //getFields Field f[] = (Math.class).getFields(); for(Field e: f) System.out.println(e); //getMethods Method m[] = c2.getMethods(); for(Method e : m) System.out.println(e); //getConstructors Constructor c[] = c2.getConstructors(); for(Constructor e : c) System.out.println(e); } }