Java by API/java.lang/Class — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 14:40, 31 мая 2010

Class: Annotation[] getAnnotations()

      
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
  String stringValue();
  int intValue();
}
@Retention(RetentionPolicy.RUNTIME)
@interface What {
  String description();
}
@What(description = "An annotation test class")
@MyAnnotation(stringValue = "for class", intValue = 100)
public class Main {
  @What(description = "An annotation test method")
  @MyAnnotation(stringValue = "Annotation Example", intValue = 100)
  public static void myMethod(String str, int i) {
  }
  public static void main(String[] arg) throws Exception {
    Main ob = new Main();
    Annotation[] annos = ob.getClass().getAnnotations();
    System.out.println("All annotations for Meta2:");
    for (Annotation a : annos)
      System.out.println(a);
  }
}





Class: forName(String classDec)

   
/*
 * Output:
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() throws java.lang.InterruptedException
 public final void java.lang.Object.wait(long,int) 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()
 * */
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class MainClass {
  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);
    }
  }
}





Class: getCanonicalName()

 
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import static java.lang.System.out;
import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.List;
public class Main {
  public static void main(String... args) {
    try {
      Class<?> c = Class.forName(args[0]);
      out.format("Class:%n  %s%n%n", c.getCanonicalName());
      out.format("Modifiers:%n  %s%n%n", Modifier.toString(c.getModifiers()));
      out.format("Type Parameters:%n");
      TypeVariable[] tv = c.getTypeParameters();
      if (tv.length != 0) {
        out.format("  ");
        for (TypeVariable t : tv)
          out.format("%s ", t.getName());
        out.format("%n%n");
      } else {
        out.format("  -- No Type Parameters --%n%n");
      }
      out.format("Implemented Interfaces:%n");
      Type[] intfs = c.getGenericInterfaces();
      if (intfs.length != 0) {
        for (Type intf : intfs)
          out.format("  %s%n", intf.toString());
        out.format("%n");
      } else {
        out.format("  -- No Implemented Interfaces --%n%n");
      }
      out.format("Inheritance Path:%n");
      List<Class> l = new ArrayList<Class>();
      printAncestor(c, l);
      if (l.size() != 0) {
        for (Class<?> cl : l)
          out.format("  %s%n", cl.getCanonicalName());
        out.format("%n");
      } else {
        out.format("  -- No Super Classes --%n%n");
      }
      out.format("Annotations:%n");
      Annotation[] ann = c.getAnnotations();
      if (ann.length != 0) {
        for (Annotation a : ann)
          out.format("  %s%n", a.toString());
        out.format("%n");
      } else {
        out.format("  -- No Annotations --%n%n");
      }
      // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    }
  }
  private static void printAncestor(Class<?> c, List<Class> l) {
    Class<?> ancestor = c.getSuperclass();
    if (ancestor != null) {
      l.add(ancestor);
      printAncestor(ancestor, l);
    }
  }
}





Class: getClasses()

   
import java.util.Arrays;
import javax.swing.JTable;
public class Main {
  public static void main(final String[] args) {
    printMemberClasses(JTable.class);
  }
  public static void printMemberClasses(final Class dataType) {
    final Class[] nestedClasses = dataType.getClasses();
    final Class[] declaredNestedClasses = dataType.getDeclaredClasses();
    final Class[] nestedInterfaces = dataType.getInterfaces();
    final Class declaringClass = dataType.getDeclaringClass();
    System.out.println("Member Class infor for: " + dataType.getName());
    System.out.println("Nested Classes: " + Arrays.asList(nestedClasses));
    System.out.println("Declared Nested Classes: " + Arrays.asList(declaredNestedClasses));
    System.out.println("Interfaces: " + Arrays.asList(nestedInterfaces));
    System.out.println("Declaring Class: " + declaringClass);
  }
}





Class: getComponentType()

   
/*
 Output:
Array of: int
Array size: 3
 * */
import java.lang.reflect.Array;
public class MainClass {
  public static void main (String args[]) {
    Object array = Array.newInstance(int.class, 3);
    
    Class type = array.getClass();
    if (type.isArray()) {
      Class elementType = type.getComponentType();
      System.out.println("Array of: " + elementType);
      System.out.println("Array size: " + Array.getLength(array));
    }
    
  }
}





Class: getConstructor(Class<?>...)

   

import java.lang.reflect.Constructor;
public class Main {
  public static void main(String[] args) {
    Constructor[] cs = String.class.getConstructors();
    for (int i = 0; i < cs.length; i++) {
      System.out.println(cs[i]);
    }
    try {
      Constructor c = String.class.getConstructor(new Class[] { String.class });
      System.out.println(c);
    } catch (SecurityException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    }
  }
}





Class: getConstructors()

   
/*
 * Output:
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() throws java.lang.InterruptedException
 public final void java.lang.Object.wait(long,int) 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()
 * */
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class MainClass {
  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);
    }
  }
}





Class: getDeclaredConstructors()

   
/*
java.util.ArrayList: 
java.util.ArrayList: Collection 
java.util.ArrayList: int 
 
 */
import java.lang.reflect.Constructor;
public class MainClass {
  public static void main(String[] args) {
    try {
      Class c = Class.forName("java.util.ArrayList");
      Constructor constructors[] = c.getDeclaredConstructors();
      for (int i = 0; i < constructors.length; i++) {
        System.out.print(constructors[i].getName() + ": ");
        Class parameters[];
        parameters = constructors[i].getParameterTypes();
        for (int j = 0; j < parameters.length; j++) {
          String s = parameters[j].getName();
          s = s.substring(s.lastIndexOf(".") + 1, s.length());
          System.out.print(s + " ");
        }
        System.out.println("");
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}





Class: getDeclaredFields()

   
/* 
ArrayList, serialVersionUID, long, private static final
ArrayList, elementData, [Ljava.lang.Object;, private transient
ArrayList, size, int, private
Arrays, INSERTIONSORT_THRESHOLD, int, private static final
BitSet, ADDRESS_BITS_PER_UNIT, int, private static final
BitSet, BITS_PER_UNIT, int, private static final
BitSet, BIT_INDEX_MASK, int, private static final
BitSet, WORD_MASK, long, private static final
BitSet, bits, [J, private
BitSet, unitsInUse, int, private transient
BitSet, serialVersionUID, long, private static final
BitSet, trailingZeroTable, [B, private static final
Collections, BINARYSEARCH_THRESHOLD, int, private static final
Collections, REVERSE_THRESHOLD, int, private static final
Collections, SHUFFLE_THRESHOLD, int, private static final
Collections, FILL_THRESHOLD, int, private static final
Collections, ROTATE_THRESHOLD, int, private static final
Collections, COPY_THRESHOLD, int, private static final
Collections, REPLACEALL_THRESHOLD, int, private static final
Collections, INDEXOFSUBLIST_THRESHOLD, int, private static final
Collections, r, java.util.Random, private static
Collections, EMPTY_SET, java.util.Set, public static final
Collections, EMPTY_LIST, java.util.List, public static final
Collections, EMPTY_MAP, java.util.Map, public static final
Collections, REVERSE_ORDER, java.util.ruparator, private static final
HashMap, DEFAULT_INITIAL_CAPACITY, int, static final
HashMap, MAXIMUM_CAPACITY, int, static final
HashMap, DEFAULT_LOAD_FACTOR, float, static final
HashMap, table, [Ljava.util.HashMap$Entry;, transient
HashMap, size, int, transient
HashMap, threshold, int, 
HashMap, loadFactor, float, final
HashMap, modCount, int, transient volatile
HashMap, NULL_KEY, java.lang.Object, static final
HashMap, entrySet, java.util.Set, private transient
HashMap, serialVersionUID, long, private static final
HashSet, serialVersionUID, long, static final
HashSet, map, java.util.HashMap, private transient
HashSet, PRESENT, java.lang.Object, private static final
WeakHashMap, DEFAULT_INITIAL_CAPACITY, int, private static final
WeakHashMap, MAXIMUM_CAPACITY, int, private static final
WeakHashMap, DEFAULT_LOAD_FACTOR, float, private static final
WeakHashMap, table, [Ljava.util.WeakHashMap$Entry;, private
WeakHashMap, size, int, private
WeakHashMap, threshold, int, private
WeakHashMap, loadFactor, float, private final
WeakHashMap, queue, java.lang.ref.ReferenceQueue, private final
WeakHashMap, modCount, int, private volatile
WeakHashMap, NULL_KEY, java.lang.Object, private static final
WeakHashMap, entrySet, java.util.Set, private transient
 *
 **/
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class MainClass {
  public static void main(String args[]) throws Exception {
    String names[] = { "ArrayList", "Arrays", "BitSet", "Collection", "Collections", "Dictionary",
        "Enumeration", "HashMap", "HashSet", "WeakHashMap" };
    for (int i = 0, n = names.length; i < n; i++) {
      String className = "java.util." + names[i];
      Class theClass = Class.forName(className);
      Field fields[] = theClass.getDeclaredFields();
      for (int j = 0, m = fields.length; j < m; j++) {
        System.out.println(names[i] + ", " + fields[j].getName() + ", "
            + fields[j].getType().getName() + ", " + Modifier.toString(fields[j].getModifiers()));
      }
    }
  }
}





Class: getDeclaredMethods()

   
/*
 * Output:
Public Methods:
 a1
 a2
 * */
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class MainClass {
  public static void main(String args[]) {
    try {
      MyClass a = new MyClass();
      Class c = a.getClass();
      System.out.println("Public Methods:");
      Method methods[] = c.getDeclaredMethods();
      for (int i = 0; i < methods.length; i++) {
        int modifiers = methods[i].getModifiers();
        if (Modifier.isPublic(modifiers)) {
          System.out.println(" " + methods[i].getName());
        }
      }
    } catch (Exception e) {
      System.out.println("Exception: " + e);
    }
  }
}
class MyClass {
  public void a1() {
  }
  public void a2() {
  }
  protected void a3() {
  }
  private void a4() {
  }
}





Class: getDeclaredMethod(String name, Class<?>... parameterTypes)

   
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {
  public static void main(String[] args) throws NoSuchMethodException,
      IllegalAccessException, InvocationTargetException {
    Method m = PrintStream.class.getDeclaredMethod("println", String.class);
    m.invoke(System.out, "Hello, World!");
  }
}





Class: getDeclaringClass()

   
import java.util.Arrays;
import javax.swing.JTable;
public class Main {
  public static void main(final String[] args) {
    printMemberClasses(JTable.class);
  }
  public static void printMemberClasses(final Class dataType) {
    final Class[] nestedClasses = dataType.getClasses();
    final Class[] declaredNestedClasses = dataType.getDeclaredClasses();
    final Class[] nestedInterfaces = dataType.getInterfaces();
    final Class declaringClass = dataType.getDeclaringClass();
    System.out.println("Member Class infor for: " + dataType.getName());
    System.out.println("Nested Classes: " + Arrays.asList(nestedClasses));
    System.out.println("Declared Nested Classes: " + Arrays.asList(declaredNestedClasses));
    System.out.println("Interfaces: " + Arrays.asList(nestedInterfaces));
    System.out.println("Declaring Class: " + declaringClass);
  }
}





Class: getEnumConstants()

 
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import static java.lang.System.out;
import java.util.Arrays;
enum Eon {
  HADEAN, ARCHAEAN, PROTEROZOIC, PHANEROZOIC
}
public class Main {
  public static void main(String... args) {
    try {
      Class<?> c = (args.length == 0 ? Eon.class : Class.forName(args[0]));
      out.format("Enum name:  %s%nEnum constants:  %s%n", c.getName(), Arrays
          .asList(c.getEnumConstants()));
      if (c == Eon.class)
        out.format("  Eon.values():  %s%n", Arrays.asList(Eon.values()));
      // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    }
  }
}





Class: getFields()

   
/*
 * Output:
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() throws java.lang.InterruptedException
 public final void java.lang.Object.wait(long,int) 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()
 * */
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class MainClass {
  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);
    }
  }
}





Class: getGenericInterfaces()

 
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import static java.lang.System.out;
import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.List;
public class Main {
  public static void main(String... args) {
    try {
      Class<?> c = Class.forName(args[0]);
      out.format("Class:%n  %s%n%n", c.getCanonicalName());
      out.format("Modifiers:%n  %s%n%n", Modifier.toString(c.getModifiers()));
      out.format("Type Parameters:%n");
      TypeVariable[] tv = c.getTypeParameters();
      if (tv.length != 0) {
        out.format("  ");
        for (TypeVariable t : tv)
          out.format("%s ", t.getName());
        out.format("%n%n");
      } else {
        out.format("  -- No Type Parameters --%n%n");
      }
      out.format("Implemented Interfaces:%n");
      Type[] intfs = c.getGenericInterfaces();
      if (intfs.length != 0) {
        for (Type intf : intfs)
          out.format("  %s%n", intf.toString());
        out.format("%n");
      } else {
        out.format("  -- No Implemented Interfaces --%n%n");
      }
      out.format("Inheritance Path:%n");
      List<Class> l = new ArrayList<Class>();
      printAncestor(c, l);
      if (l.size() != 0) {
        for (Class<?> cl : l)
          out.format("  %s%n", cl.getCanonicalName());
        out.format("%n");
      } else {
        out.format("  -- No Super Classes --%n%n");
      }
      out.format("Annotations:%n");
      Annotation[] ann = c.getAnnotations();
      if (ann.length != 0) {
        for (Annotation a : ann)
          out.format("  %s%n", a.toString());
        out.format("%n");
      } else {
        out.format("  -- No Annotations --%n%n");
      }
      // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    }
  }
  private static void printAncestor(Class<?> c, List<Class> l) {
    Class<?> ancestor = c.getSuperclass();
    if (ancestor != null) {
      l.add(ancestor);
      printAncestor(ancestor, l);
    }
  }
}





Class: getGenericSuperclass()

   
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class MainClass {
  public static void main(String args[]) throws Exception {
    Type type = StringList.class.getGenericSuperclass();
    System.out.println(type); // java.util.ArrayList<java.lang.String>
    ParameterizedType pt = (ParameterizedType) type;
    System.out.println(pt.getActualTypeArguments()[0]);
  }
}
class StringList extends ArrayList<String> {
}





Class: getInterfaces()

   

import java.util.Arrays;
import javax.swing.JTable;
public class Main {
  public static void main(final String[] args) {
    printMemberClasses(JTable.class);
  }
  public static void printMemberClasses(final Class dataType) {
    final Class[] nestedClasses = dataType.getClasses();
    final Class[] declaredNestedClasses = dataType.getDeclaredClasses();
    final Class[] nestedInterfaces = dataType.getInterfaces();
    final Class declaringClass = dataType.getDeclaringClass();
    System.out.println("Member Class infor for: " + dataType.getName());
    System.out.println("Nested Classes: " + Arrays.asList(nestedClasses));
    System.out.println("Declared Nested Classes: " + Arrays.asList(declaredNestedClasses));
    System.out.println("Interfaces: " + Arrays.asList(nestedInterfaces));
    System.out.println("Declaring Class: " + declaringClass);
  }
}





Class: getMethods()

   
/*
 * Output:
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() throws java.lang.InterruptedException
 public final void java.lang.Object.wait(long,int) 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()
 * */
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class MainClass {
  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);
    }
  }
}





Class: getModifiers()

 

import java.lang.reflect.Modifier;
public class Main {
  public static void main(String[] args) throws Exception {
    getClassModifier(String.class);
    getClassModifier(TestA.class);
    getClassModifier(TestB.class);
  }
  private static void getClassModifier(Class clazz) {
    int modifier = clazz.getModifiers();

    if (Modifier.isPrivate(modifier)) {
      System.out.println(clazz.getName() + " class modifier is private");
    }
  }
  protected static final class TestA {
  }
  private abstract class TestB {
  }
}





Class: getName()

   
/*
 * Output: 
x is object of type: Class1
y is object of type: Class2
y"s superclass is Class1
 *  
 */
class Class1 {
  int a;
  float b;
}
class Class2 extends Class1 {
  double c;
}
public class MainClass {
  public static void main(String args[]) {
    Class1 x = new Class1();
    Class2 y = new Class2();
    Class clObj;
    clObj = x.getClass(); // get Class reference
    System.out.println("x is object of type: " + clObj.getName());
    clObj = y.getClass(); // get Class reference
    System.out.println("y is object of type: " + clObj.getName());
    clObj = clObj.getSuperclass();
    System.out.println("y"s superclass is " + clObj.getName());
  }
}





Class: getPackage()

   
public class Main {
    public static void main(String[] args) {
        System.out.println(Main.class.getName());
        System.out.println(int[].class.getName()); 
        System.out.println(Main[].class.getName());      
        System.out.println(Main.class.getPackage()); 
    }
}





Class: getProtectionDomain()

 
public class Main {
  public static void main(String args[]) {
    Main m = new Main();
    System.out.println(m.getClass().getName() + " is loaded from "
        + m.getClass().getProtectionDomain().getCodeSource().getLocation());
  }
}





Class: getResourceAsStream(String name)

   
import java.awt.Image;
import java.awt.Toolkit;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public final class MainClass {
  private MainClass() {
  }
  public static Image getImage(Class relativeClass, String filename) {
    Image returnValue = null;
    InputStream is = relativeClass.getResourceAsStream(filename);
    if (is != null) {
      BufferedInputStream bis = new BufferedInputStream(is);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      try {
        int ch;
        while ((ch = bis.read()) != -1) {
          baos.write(ch);
        }
        returnValue = Toolkit.getDefaultToolkit().createImage(
            baos.toByteArray());
      } catch (IOException exception) {
        System.err.println("Error loading: " + filename);
      }
    }
    return returnValue;
  }
}





Class: getResource(String name) (absolute from the classpath)

   
import java.net.URL;
public class MainClass {
  public static void main(String[] args) throws Exception {
    // absolute from the classpath
    URL url = MainClass.class.getResource("/mypackage/foo.txt");
    System.out.println(url);
    // relative to the class location
    url = MainClass.class.getResource("foo.txt");
    System.out.println(url);
    // another relative document
    url = MainClass.class.getResource("docs/bar.txt");
    System.out.println(url);
  }
}





Class: getResource(String name) (relative to the class location)

   
import java.net.URL;
public class MainClass {
  public static void main(String[] args) throws Exception {
    // absolute from the classpath
    URL url = MainClass.class.getResource("/mypackage/foo.txt");
    System.out.println(url);
    // relative to the class location
    url = MainClass.class.getResource("foo.txt");
    System.out.println(url);
    // another relative document
    url = MainClass.class.getResource("docs/bar.txt");
    System.out.println(url);
  }
}





Class: getSuperclass()

   
/*
 * Output: 
x is object of type: Class1
y is object of type: Class2
y"s superclass is Class1
 *  
 */
class Class1 {
  int a;
  float b;
}
class Class2 extends Class1 {
  double c;
}
public class MainClass {
  public static void main(String args[]) {
    Class1 x = new Class1();
    Class2 y = new Class2();
    Class clObj;
    clObj = x.getClass(); // get Class reference
    System.out.println("x is object of type: " + clObj.getName());
    clObj = y.getClass(); // get Class reference
    System.out.println("y is object of type: " + clObj.getName());
    clObj = clObj.getSuperclass();
    System.out.println("y"s superclass is " + clObj.getName());
  }
}





Class: getTypeParameters()

   
import java.lang.reflect.TypeVariable;
import java.util.List;
public class MainClass {
  public static void main(String args[]) throws Exception {
    TypeVariable[] tv = List.class.getTypeParameters();
    System.out.println(tv[0].getName()); 
  }
}





Class: isArray()

   
/*
 Output:
Array of: int
Array size: 3
 * */
import java.lang.reflect.Array;
public class MainClass {
  public static void main (String args[]) {
    Object array = Array.newInstance(int.class, 3);
    
    Class type = array.getClass();
    if (type.isArray()) {
      Class elementType = type.getComponentType();
      System.out.println("Array of: " + elementType);
      System.out.println("Array size: " + Array.getLength(array));
    }
    
  }
}





Class: isAssignableFrom(Class<?> cls)

   

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Main {
  public static boolean isNumber(final Class dataType) {
    return Number.class.isAssignableFrom(dataType);
  }
  public static void main(final String[] args) {
    final Set classes = new HashSet();
    classes.add(Class.class);
    System.out.println("Using isAssignableFrom:");
    useAssignable(classes);
    System.out.println("\nUsing isInstance:");
    useIsInstance(classes);
  }

  public static void useAssignable(final Set inputSet) {
    final Iterator iter = inputSet.iterator();
    Object obj = null;
    while (iter.hasNext()) {
      obj = iter.next();
      if (obj != null) {
        if (Number.class.isAssignableFrom(obj.getClass())) {
          System.out.println(obj);
        }
      }
    }
  }

  public static void useIsInstance(final Set inputSet) {
    final Iterator iter = inputSet.iterator();
    Object obj = null;
    while (iter.hasNext()) {
      obj = iter.next();
      if (Number.class.isInstance(obj)) {
        System.out.println(obj);
      }
    }
  }
  public static void useIsInstance2(final Class dataType, final Set inputSet) {
    if (dataType == null) {
      throw new NullPointerException();
    }
    final Iterator iter = inputSet.iterator();
    Object obj = null;
    while (iter.hasNext()) {
      obj = iter.next();
      if (dataType.isInstance(obj)) {
        System.out.println(obj);
      }
    }
  }
}





Class: isEnum()

 
import org.xml.sax.XMLReader;

public class Main {
    public static void main(String[] args) {
        System.out.println(Size.class.isEnum());
        System.out.println(String.class.isEnum());
        System.out.println(String.class.isInstance("Test"));     
        System.out.println(XMLReader.class.isInterface());          
    }
}
enum Size {
  S, M, L, XL, XXL, XXXL;
}





Class: isInstance(Object obj)

 

import org.xml.sax.XMLReader;

public class Main {
    public static void main(String[] args) {
        System.out.println(Size.class.isEnum());
        System.out.println(String.class.isEnum());
        System.out.println(String.class.isInstance("Test"));     
        System.out.println(XMLReader.class.isInterface());          
    }
}
enum Size {
  S, M, L, XL, XXL, XXXL;
}





Class: isInterface()

   
/*
java.util.List is an interface
 */
public class MainClass {
  public static void main(String[] unused) {
    try {
      String n = "java.util.List";
      Class c = Class.forName(n);
      if (c.isInterface()) {
        System.out.println(n + " is an interface");
      } else {
        System.out.println(n + " is not an interface");
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}





Class: Method getMethod(String name, Class<?>... parameterTypes)

      
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
  String stringValue();
  int intValue();
}
public class Main {
  @MyAnnotation(stringValue = "Annotation Example", intValue = 100)
  public static void myMethod() {
  }
  public static void main(String[] a) throws Exception {
    Main ob = new Main();
    Class c = ob.getClass();
    Method m = c.getMethod("myMethod");
    MyAnnotation anno = m.getAnnotation(MyAnnotation.class);
    System.out.println(anno.stringValue() + " " + anno.intValue());
  }
}





Class: newInstance()

   
public class Main {
    public static void main(String[] args) {
        try {
            String pc = String.class.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}