Java中的java.lang.Class API 詳解

且將新火試新茶,詩酒趁年華。

https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/java/java04.jpg

概述

Class是一個位於java.lang包下面的一個類,在Java中每個類實例都有對應的Class對象。類對象是由Java虛擬機(JVM)自動構造的。

Class類的方法經常在反射時被調用。

創建Class對象

有三種方法可以創建Class對象

  1. Class.forName(“className”):因爲Class類沒有公共的構造方法,所以存在一個靜態的方法返回Class對象,即Class.forName()用於創建Class對象。要創建的Class對象的類名在運行時確定,不存在則拋出ClassNotFoundException。(注意className爲類的完整包名)
Class.forName("java.lang.String")
  1. Myclass.class:當我們在類名後面跟上.class時,就會返回當前類的Class對象。它主要應用於原始數據類型,並且僅在我們知道類的名稱時才使用。要創建的Class對象的類名在編譯時確定
Class c2 = String.class;

請注意,此方法與類名一起使用,而不是與類實例一起使用

A a = new A();   // Class A 的實例a
Class c = A.class; // 正確用法
Class c = a.class; //編譯出錯
  1. obj.getClass() : 此方法存在時Object類中,它返回此obj對象的運行時類。
String str = new String("string");
Class c3 = str.getClass();

Class對象裏面的方法

String toString()

此方法將Class對象轉換爲字符串。它返回字符串表示形式,即字符串“class”或“interface”,後跟空格,然後是類的含包名名稱。如果Class對象表示基本類型,則此方法返回基本類型的名稱,如果它表示void,則返回“void”

描述:

語法 :
public String toString()
參數 :
NA
返回 :
a string representation of this class object.
重寫 :
toString in class Object

測試類:

public class ToStringTest {
    public static void main(String[] args) throws ClassNotFoundException {
        Class c1 = Class.forName("java.lang.String");
        Class c2 = int.class;
        Class c3 = void.class;
        System.out.println("Class represented by c1: "+c1.toString());
        System.out.println("Class represented by c2: "+c2.toString());
        System.out.println("Class represented by c3: "+c3.toString());
    }
}

輸出:

Class represented by c1: class java.lang.String
Class represented by c2: int
Class represented by c3: void

String toGenericString()

返回描述此類的字符串,包括有關修飾符和類型參數的信息。

描述:

語法 :
public String toGenericString()
參數 :
NA
返回 :
a string describe of this class object.

測試類:

public class ToGenericStringTest {
    public static void main(String[] args) throws ClassNotFoundException {
        Class c1 = Class.forName("java.lang.String");
        Class c2 = int.class;
        Class c3 = void.class;
        System.out.println("Class represented by c1: "+c1.toGenericString());
        System.out.println("Class represented by c2: "+c2.toGenericString());
        System.out.println("Class represented by c3: "+c3.toGenericString());
    }
}

輸出:

Class represented by c1: public final class java.lang.String
Class represented by c2: int
Class represented by c3: void

Class<?> forName(String className)

返回與給定字符串名稱的類或接口相關聯的 類對象。

描述:

語法 :
public static Class<?> forName(String className) throws ClassNotFoundException
參數 :
className -含包名
返回 :
返回指定包名的class對象
異常:
ClassNotFoundException
......

測試類:

public class ToClassForNameTest {
    public static void main(String[] args) throws ClassNotFoundException {
        Class c1 = Class.forName("java.lang.String");
    }
}

輸出:

Class<?> forName(String className,boolean initialize, ClassLoader loader)

使用給定的類加載器返回與給定字符串名稱的類或接口相關聯的類對象。如果參數loader爲空,則通過引導類加載器加載該類。只有當initialize參數爲true並且尚未被初始化時,該類才被初始化。

描述:

語法 :
public static Class<?> forName(String className,boolean initialize, ClassLoader loader)
throws ClassNotFoundException
參數 :
className -含包名
initialize - 如果true該類將被初始化。
loader  - 類加載器
返回 :
返回指定包名的class對象
異常:
ClassNotFoundException
......

測試類:

public class ToClassForNameTest {
    public static void main(String[] args) throws ClassNotFoundException {
        Class myClass = Class.forName("Test");
        ClassLoader loader = myClass.getClassLoader();
        Class c = Class.forName("java.lang.String",true,loader)
    }
}

輸出:

T newInstance()

此方法創建此Class對象表示的類的新實例。通過具有空參數列表的新表達式創建類。如果尚未初始化,則初始化該類。

描述:

語法 :
public T newInstance() throws InstantiationException,IllegalAccessException
參數 :
NA
返回 :
由此對象表示的類的新分配實例
異常:
IllegalAccessException
......

測試類:

public class NewInstanceTest {
    public static void main(String[] args) throws ClassNotFoundException {
      Class c1 = Class.forName("java.lang.String");
      Object instance = c1.newInstance();
      System.out.println("instance class : " + instance.getClass());
    }
}

輸出:

instance class : class java.lang.String

boolean isInstance(Object obj)

此方法確定指定的Object是否與此Class表示的對象分配兼容。它相當於java中的instanceof運算符

描述:

語法 :
public boolean isInstance(Object obj)
參數 :
obj - the object to check
返回 :
true if obj is an instance of this class else return false
異常:

測試類:

public class IsInstanceTest {
    public static void main(String[] args) throws ClassNotFoundException {
        Class c = Class.forName("java.lang.String");
        String url = "http://niocoder.com";
        int i = 10;
        boolean b1 = c.isInstance(url);
        boolean b2 = c.isInstance(i);
        System.out.println("is url instance of String : " + b1);
        System.out.println("is i instance of String : " + b2);
    }
}

輸出:

is url instance of String : true
is i instance of String : false

boolean isAssignableFrom(Class<?> cls)

此方法確定此Class對象表示的類或接口是否與指定的Class參數表示的類或接口相同,或者是超類或超接口。

描述:

語法 :
public boolean isAssignableFrom(Class<?> cls)
參數 :
cls - the Class object to be checked
返回 :
true if objects of the type cls can be assigned to objects of this class

測試類:

public class IsAssignableFrom extends Thread {
    public static void main(String[] args) throws Exception {
        Class myClass = Class.forName("com.niocoder.test.java.method.IsAssignableFrom");
        Class c1 = Class.forName("java.lang.Thread");
        Class c2 = Class.forName("java.lang.String");

        boolean b1 = c1.isAssignableFrom(myClass);
        boolean b2 = c2.isAssignableFrom(myClass);

        System.out.println("is Thread class Assignable from IsAssignableFrom : " + b1);
        System.out.println("is String class Assignable from Test : " + b2);
    }
}

輸出:

is Thread class Assignable from IsAssignableFrom : true
is String class Assignable from Test : false

boolean isInterface()

此方法確定指定的Class對象是否表示接口類型

描述:

語法 :
public boolean isInterface()
參數 :
NA
返回 :
return true if and only if this class represents an interface type else return false

測試類:

public class IsInterfaceTest {
    public static void main(String[] args) throws Exception {
        Class c1 = Class.forName("java.lang.String");
        Class c2 = Class.forName("java.lang.Runnable");
        boolean b1 = c1.isInterface();
        boolean b2 = c2.isInterface();
        System.out.println("is java.lang.String an interface : " + b1);
        System.out.println("is java.lang.Runnable an interface : " + b2);
    }
}

輸出:

is java.lang.String an interface : false
is java.lang.Runnable an interface : true

boolean isPrimitive()

此方法確定指定的Class對象是否表示基本類型。即boolean , byte , char , short , int , long , float和double 。

描述:

語法 :
public boolean isPrimitive()
參數 :
NA
返回 :
return true if and only if this class represents a primitive type else return false

測試類:

public class IsPrimitiveTest {
    public static void main(String[] args) {
        Class c1 = int.class;
        Class c2 = IsPrimitiveTest.class;
        boolean b1 = c1.isPrimitive();
        boolean b2 = c2.isPrimitive();

        System.out.println("is " + c1.toString() + " primitive : " + b1);
        System.out.println("is " + c2.toString() + " primitive : " + b2);
    }
}

輸出:

is int primitive : true
is class com.niocoder.test.java.method.IsPrimitiveTest primitive : false

boolean isArray()

此方法確定指定的Class對象是否表示數組類。

描述:

語法 :
public boolean isArray()
參數 :
NA
返回 :
return true if and only if this class represents an array type else return false

測試類:

public class IsArrayTest {
    public static void main(String[] args) {
        int a[] = new int[2];
        Class c1 = a.getClass();
        Class c2 = IsArrayTest.class;

        boolean b1 = c1.isArray();
        boolean b2 = c2.isArray();

        System.out.println("is "+c1.toString()+" an array : " + b1);
        System.out.println("is "+c2.toString()+" an array : " + b2);
    }
}

輸出:

is class [I an array : true
is class com.niocoder.test.java.method.IsArrayTest an array : false

boolean isAnonymousClass()

當且僅當此類是匿名類時,此方法才返回true。匿名類與本地類類似,只是它們沒有名稱

描述:

語法 :
public boolean isAnonymousClass()
參數 :
NA
返回 :
true if and only if this class is an anonymous class.false,otherwise.

boolean isLocalClass()

當且僅當此類是本地類時,此方法才返回true。本地類是在Java代碼塊中本地聲明的類,而不是類的成員。

描述:

語法 :
public boolean isLocalClass()
參數 :
NA
返回 :
true if and only if this class is a local class.false,otherwise.

boolean isMemberClass()

當且僅當此類是Member類時,此方法返回true。

描述:

語法 :
public boolean isMemberClass()
參數 :
NA
返回 :
true if and only if this class is a Member class.false,otherwise.

boolean isEnum()

當且僅當此類在源代碼中聲明爲枚舉時,此方法才返回true

描述:

語法 :
public boolean isEnum()
參數 :
NA
返回 :
true iff this class was declared as an enum in the source code.false,otherwise.

boolean isAnnotation()

此方法確定此Class對象是否表示註釋類型。請注意,如果此方法返回true,則isInterface()方法也將返回true,因爲所有註釋類型也是接口

描述:

語法 :
public boolean isAnnotation()
參數 :
NA
返回 :
return true if and only if this class represents an annotation type else return false

測試類:

public class IsTest {

@interface B
{
    // Annotation element definitions
}

//枚舉
enum Color {
    RED, GREEN, BLUE;
}

//  Member class
class A {
}

public static void main(String[] args) {
    // 匿名類
    IsTest t1 = new IsTest() {

    };

    Class c1 = t1.getClass();
    Class c2 = IsTest.class;
    Class c3 = A.class;
    Class c4 = Color.class;
    Class c5 = B.class;

    boolean b1 = c1.isAnonymousClass();
    System.out.println("is " + c1.toString() + " an anonymous class : " + b1);
    boolean b2 = c2.isLocalClass();
    System.out.println("is " + c2.toString() + " a local class : " + b2);
    boolean b3 = c3.isMemberClass();
    System.out.println("is " + c3.toString() + " a member class : " + b3);
    boolean b4 = c4.isEnum();
    System.out.println("is " + c3.toString() + " a Enum class : " + b4);
    boolean b5 = c5.isAnnotation();
    System.out.println("is " + c3.toString() + " an annotation  : " + b5);
}

}

輸出:

is class com.niocoder.test.java.method.IsTest$1 an anonymous class : true
is class com.niocoder.test.java.method.IsTest a local class : false
is class com.niocoder.test.java.method.IsTest$A a member class : true
is class com.niocoder.test.java.method.IsTest$A a Enum class : true
is class com.niocoder.test.java.method.IsTest$A an annotation  : true

String getName()

返回由 類對象表示的實體(類,接口,數組類,原始類型或空白)的名稱(含包明),作爲 String 。

描述:

語法 :
public String getName()
參數 :
NA
返回 :
returns the name of the name of the entity represented by this object.

String getSimpleName()

此方法返回源代碼中給出的基礎類的名稱(不含包名)。如果基礎類是匿名類,則返回空字符串

描述:

語法 :
public String getSimpleName()
參數 :
NA
返回 :
the simple name of the underlying class

測試類:

public class GetNameTest {
    public static void main(String[] args)
    {
        Class c = GetNameTest.class;

        System.out.print("Class Name associated with c : ");
        System.out.println(c.getName());
        System.out.println(c.getSimpleName());
    }
}

輸出:

Class Name associated with c : com.niocoder.test.java.method.GetNameTest
GetNameTest

ClassLoader getClassLoader()

此方法返回此類的類加載器。如果類加載器是bootstrap類加載器,那麼此方法返回null,因爲引導類加載器是用C,C ++等本機語言實現的。如果此對象表示基本類型或void,則返回null

描述:

語法 :
public ClassLoader getClassLoader()
參數 :
NA
返回 :
the class loader that loaded the class or interface represented by this object
represented by this object.

TypeVariable<Class>[ ] getTypeParameters()

此方法返回一個TypeVariable對象數組,該對象表示由此GenericDeclaration對象表示的泛型聲明聲明的類型變量,按聲明順序

描述:

語法 :
public TypeVariable<Class<T>>[] getTypeParameters()
參數 :
NA
返回 :
an array of TypeVariable objects that represent the type variables declared
by this generic declaration represented by this object.

測試類:

public class GetClassLoaderTest {
    public static void main(String[] args) throws Exception {
        {
            Class myClass = Class.forName("com.niocoder.test.java.method.GetClassLoaderTest");
            Class c1 = Class.forName("java.lang.String");
            Class c2 = int.class;
            System.out.print("GetClassLoaderTest class loader : ");
            System.out.println(myClass.getClassLoader());
            System.out.print("String class loader : ");
            System.out.println(c1.getClassLoader());

            System.out.print("primitive int loader : ");
            System.out.println(c2.getClassLoader());
        }

        {
            Class c = Class.forName("java.util.Set");
            TypeVariable[] tv = c.getTypeParameters();
            System.out.println("TypeVariables in "+c.getName()+" class : ");
            for (TypeVariable typeVariable : tv)
            {
                System.out.println(typeVariable);
            }
        }

    }
}

輸出:

GetClassLoaderTest class loader : sun.misc.Launcher$AppClassLoader@18b4aac2
String class loader : null
primitive int loader : null
TypeVariables in java.util.Set class :
E

Class<? super T> getSuperclass()

此方法返回表示此Class所表示的實體(類,接口,基本類型或void)的超類的Class。如果此Class表示Object類,接口,基本類型或void,則返回null。如果此對象表示數組類,則返回表示Object類的Class對象。

描述:

語法 :
public Class<? super T> getSuperclass()
參數 :
NA
返回 :
the superclass of the class represented by this object

Type getGenericSuperclass()

此方法返回表示此Class所表示的實體(類,接口,基本類型或void)的直接超類的Type。如果此Class表示Object類,接口,基本類型或void,則返回null。如果此對象表示數組類,則返回表示Object類的Class對象。

描述:

語法 :
public Type getGenericSuperclass()
參數 :
NA
返回 :
athe superclass of the class represented by this object

Class<?>[] getInterfaces()

此方法返回由此對象表示的類或接口實現的接口。如果此對象表示不實現接口的類或接口,則該方法返回長度爲0的數組。如果此對象表示基本類型或void,則該方法返回長度爲0的數組。

描述:

語法 :
public Class<?>[] getInterfaces()
參數 :
NA
返回 :
an array of interfaces implemented by this class.

Package getPackage()

此方法返回此類的包。

描述:

語法 :
public Package getPackage()
參數 :
NA
返回 :
the package of the class,
or null if no package information is available
from the archive or codebase.

測試類:

public class GetSuperClassTest {
    public static void main(String[] args) throws Exception {
        System.out.println("getSuperclass-----------------------------------------");
        {
            Class myClass = GetSuperClassTest.class;
            Class c1 = Class.forName("com.niocoder.test.java.method.A");
            Class c2 = Class.forName("com.niocoder.test.java.method.B");
            Class c3 = Class.forName("java.lang.Object");
            System.out.print("GetSuperClassTest superclass : ");
            System.out.println(myClass.getSuperclass());
            System.out.print("A superclass : ");
            System.out.println(c1.getSuperclass());
            System.out.print("B superclass : ");
            System.out.println(c2.getSuperclass());
            System.out.print("Object superclass : ");
            System.out.println(c3.getSuperclass());
        }

        System.out.println("getGenericSuperclass-----------------------------------------");
        {
            Class myClass = GetSuperClassTest.class;
            Class c1 = Class.forName("java.util.ArrayList");
            Class c3 = Class.forName("java.lang.Object");
            System.out.print("GetSuperClassTest superclass : ");
            System.out.println(myClass.getGenericSuperclass());
            System.out.print("ArrayList superclass : ");
            System.out.println(c1.getGenericSuperclass());
            System.out.print("Object superclass : ");
            System.out.println(c3.getGenericSuperclass());
        }

        System.out.println("getInterfaces-----------------------------------------");
        {
            Class c1 = Class.forName("com.niocoder.test.java.method.D");
            Class c2 = Class.forName("java.lang.String");
            Class c1Interfaces[] = c1.getInterfaces();
            Class c2Interfaces[] = c2.getInterfaces();
            System.out.println("interfaces implemented by D class : ");
            for (Class class1 : c1Interfaces) {
                System.out.println(class1);
            }

            System.out.println("interfaces implemented by String class : ");
            for (Class class1 : c2Interfaces) {
                System.out.println(class1);
            }
        }

        System.out.println("getPackage-----------------------------------------");
        {
            Class c1 = Class.forName("java.lang.String");
            Class c2 = Class.forName("java.util.ArrayList");
            System.out.println(c1.getPackage());
            System.out.println(c2.getPackage());
        }
    }
}

class A {

}

class B extends A {

}

interface C {

}

interface D extends C {

}

輸出:

getSuperclass-----------------------------------------
GetSuperClassTest superclass : class java.lang.Object
A superclass : class java.lang.Object
B superclass : class com.niocoder.test.java.method.A
Object superclass : null
getGenericSuperclass-----------------------------------------
GetSuperClassTest superclass : class java.lang.Object
ArrayList superclass : java.util.AbstractList<E>
Object superclass : null
getInterfaces-----------------------------------------
interfaces implemented by D class :
interface com.niocoder.test.java.method.C
interfaces implemented by String class :
interface java.io.Serializable
interface java.lang.Comparable
interface java.lang.CharSequence
getPackage-----------------------------------------
Disconnected from the target VM, address: '127.0.0.1:59273', transport: 'socket'
package java.lang, Java Platform API Specification, version 1.8
package java.util, Java Platform API Specification, version 1.8

Field[] getFields()

此方法返回一個Field對象數組,該對象反映此Class對象表示的類(及其所有超類)或接口(及其所有超類)的所有可訪問公共字段

描述:

語法 :
public Field[] getFields()  throws SecurityException
參數 :
NA
返回 :
the array of Field objects representing the public fields
and  array of length 0 if the class or interface has no accessible public fields
or if this Class object represents a primitive type or void.

測試類:

public class GetFieldsTest {
    public static void main(String[] args) throws Exception {
        Class c1 = Class.forName("java.lang.Integer");
        Field F[] = c1.getFields();

        System.out.println("Below are the fields of Integer class : ");
        for (Field field : F) {
            System.out.println(field);
        }
    }
}


輸出:

Below are the fields of Integer class :
public static final int java.lang.Integer.MIN_VALUE
public static final int java.lang.Integer.MAX_VALUE
public static final java.lang.Class java.lang.Integer.TYPE
public static final int java.lang.Integer.SIZE
public static final int java.lang.Integer.BYTES

Method[] getMethods()

此方法返回一個Method對象數組,這些對象反映了類或接口的所有可訪問的公共方法,以及從此Class對象表示的超類和超級接口繼承的方法。

描述:

語法 :
public Method[] getMethods() throws SecurityException
參數 :
NA
返回 :
the array of Method objects representing the public methods
and  array of length 0 if the class or interface has no accessible public method
or if this Class object represents a primitive type or void.

測試類:

public class GetMethodsTest {
    public static void main(String[] args) throws Exception {
        Class c1 = Class.forName("java.lang.Object");
        Method M[] = c1.getMethods();

        System.out.println("Below are the methods of Object class : ");
        for (Method method : M) {
            System.out.println(method);
        }
    }
}


輸出:

Below are the methods of Object class :
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 boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()

Constructor<?>[] getConstructors()

此方法返回一個Constructor對象數組,這些對象反映此Class對象所表示的類的所有公共構造函數

描述:

語法 :
public Constructor<?>[] getConstructors() throws SecurityException
參數 :
NA
返回 :
the array of Constructor objects representing the public constructors of this class
and  array of length 0 if the class or interface has no accessible public constructor
or if this Class object represents a primitive type or void.

測試類:

public class GetConstructorsTest {
    public static void main(String[] args) throws Exception {
        Class c1 = Class.forName("java.lang.Boolean");
        Constructor C[] = c1.getConstructors();

        System.out.println("Below are the constructors of Boolean class :");
        for (Constructor constructor : C) {
            System.out.println(constructor);
        }
    }
}

輸出:

public java.lang.Boolean(boolean)
public java.lang.Boolean(java.lang.String)

Field getField(String fieldName)

此方法返回一個Field對象,該對象反映此Class對象所表示的類或接口的指定公共成員字段

描述:

語法 :
public Field getField(String fieldName) throws NoSuchFieldException,SecurityException
參數 :
fieldName -  the field name
返回 :
the Field object of this class specified by name

Method getMethod(String methodName,Class… parameterTypes)

此方法返回一個Method對象,該對象反映此Class對象所表示的類或接口的指定公共成員方法

描述:

語法 :
public Method getMethod(String methodName,Class... parameterTypes) throws
NoSuchFieldException,SecurityException
參數 :
methodName -  the method name
parameterTypes - the list of parameters
返回 :
the method object of this class specified by name

Constructor<?> getConstructor(Class<?>… parameterTypes)

此方法返回一個Constructor對象,該對象反映此Class對象所表示的類的指定公共構造函數.parameterTypes參數是一個Class對象的數組,用於按聲明的順序標識構造函數的形式參數類型

描述:

語法 :
public Constructor<?> getConstructor(Class<?>... parameterTypes)
throws NoSuchMethodException,SecurityException
參數 :
parameterTypes - the list of parameters
返回 :
the Constructor object of the public constructor that matches the specified parameterTypes

測試類:

public class GetFieldsNameTest {
    public static void main(String[] args) throws Exception {
        System.out.println("getField--------------------------------------------");
        {
            Class c1 = Class.forName("java.lang.Integer");

            Field f = c1.getField("MIN_VALUE");

            System.out.println("public field in Integer class with MIN_VALUE name :");
            System.out.println(f);
        }
        System.out.println("getMethod--------------------------------------------");
        {
            Class c1 = Class.forName("java.lang.Integer");
            Class c2 = Class.forName("java.lang.String");
            Method m = c1.getMethod("parseInt", c2);

            System.out.println("method in Integer class specified by parseInt : ");
            System.out.println(m);
        }
        System.out.println("getConstructor--------------------------------------------");
        {
            Class c1 = Class.forName("java.lang.Integer");
            Class c2 = Class.forName("java.lang.String");
            Constructor c = c1.getConstructor(c2);

            System.out.println("Constructor in Integer class & String parameterType:");
            System.out.println(c);
        }
    }
}

輸出:

getField--------------------------------------------
public field in Integer class with MIN_VALUE name :
public static final int java.lang.Integer.MIN_VALUE
getMethod--------------------------------------------
method in Integer class specified by parseInt :
public static int java.lang.Integer.parseInt(java.lang.String) throws java.lang.NumberFormatException
getConstructor--------------------------------------------
Constructor in Integer class & String parameterType:
public java.lang.Integer(java.lang.String) throws java.lang.NumberFormatException

T cast(Object obj)

此方法用於將對象強制轉換爲此Class對象表示的類或接口。

描述:

語法 :
public T cast(Object obj)
參數 :
obj - the object to be cast
返回 :
the object after casting, or null if obj is null

Class<? extends U> asSubclass(Class clazz)

此方法用於轉換此Class對象以表示由指定的類對象表示的類的子類。它始終返回對此類對象的引用

描述:

語法 :
public <U> Class<? extends U> asSubclass(Class<U> class)
參數 :
clazz - the superclass object to be cast
返回 :
this Class object, cast to represent a subclass of the specified class object.

測試類:

public class CastTest {
    public static void main(String[] args) {
        {
            A1 a = new A1();
            System.out.println(a.getClass());
            B1 b = new B1();
            a = A1.class.cast(b);
            System.out.println(a.getClass());
        }

        {
            A1 a = new A1();
            Class superClass = a.getClass();
            B1 b = new B1();
            Class subClass = b.getClass();
            Class cast = subClass.asSubclass(superClass);
            System.out.println(cast);
        }

    }
}

class A1 {

}

class B1 extends A1 {

}

輸出:

class com.niocoder.test.java.method.A1
class com.niocoder.test.java.method.B1
class com.niocoder.test.java.method.B1

參考鏈接


Java.lang.Class class in Java | Set 1

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章