Use class Class - Java reflection understood that (a)

Use class Class - Java reflection understood that (a)

concept

Here describes a few basic concepts:

  1. In the object-oriented world, all things are objects. (Except in the Java language in a static member of a common data type)

  2. Class is also an object class is java.lang.Classan instance of an object.

  3. What class type?

    Class type can be simply understood as the class type. Everything in Java objects, each class is our definition java.lang.Classof an object class, the object is the class of the class type, namely Class object.

  4. There are three ways to get the Class object:
    • Known class name 类名.class( )
    • Known class object 对象.getClass()( )
    • Class class (class type) is provided in a method called forName ( Class.forName("类名"))

Show

We demonstrate through concrete to describe three ways to get the Class object:

import com.demo.reflect;

/** 创建一个 Foo 类 **/
class Foo{  
    void print(){
        System.out.println("foo");
    }
}

/** 演示类 ClassDemo1 **/
public class ClassDemo1 {
    public static void main(String[] args) {
        //Foo的实例对象用 fool 表示
        Foo foo1 = new Foo();
        //Foo 这个类 也是一个实例对象
        //任何一个类都是Class的实例对象,这个实例对象有三种表示方式
        
        // c1, c2, c3 表示了 Foo 类的类类型(class type),一个类只可能是Class类的一个实例对象,即 c1 = c2 = c3,三次得到的Class对象都是同一个
        
        //第一种表示方式 ---> 实际在告诉我们任何一个类都有一个隐含的静态成员变量class
        Class c1 = Foo.class;
        
        //第二中表达方式 ---> 已经知道该类的对象通过getClass方法获取
        Class c2 = foo1.getClass();
        
        System.out.println(c1 == c2);
        
        //第三种表达方式
        Class c3 = null;
        try {
            c3 = Class.forName("com.demo.reflect.Foo");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        System.out.println(c2==c3);
        
        //我们完全可以通过类的类类型创建该类的对象实例 ---> 通过c1 or c2 or c3 创建 Foo 的实例对象
        try {
            Foo foo = (Foo) c1.newInstance();//需要有无参数的构造方法
            foo.print();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            
    }
}

Operating results as follows:

true
true
foo

Finish.

Guess you like

Origin www.cnblogs.com/weixuqin/p/11220729.html