你的位置:首页 > Java教程

[Java教程]反射1


Class类(java.lang.Class)

public final class Class<T>extends Objectimplements Serializable, GenericDeclaration, Type, AnnotatedElement

Class对象的三种实例化模式

  1. 对象.getClass();
  2. 类.class;
  3. Class.forName(String className)

    public static Class<?> forName(String className) throws ClassNotFoundException

 

Class类对象(类)的实例化形式

Class类的对象.newInstance(); 

				public T newInstance()throws InstantiationException, IllegalAccessException

 

反射的一般实例:

class Phone {

    public Phone() {

        System.out.println("Phone类的构造方法");

    }

    public String toString() {

        return "是一部手机";

    }

}

public class Test {

    public static void main(String[] args) throws Exception {

        Class<Phone> cls = Phone.class;

        Phone p2 = cls.newInstance();

        System.out.println("p2: " + p2);

    }

}