且将新火试新茶,诗酒趁年华。java
Class
是一个位于java.lang
包下面的一个类,在Java
中每一个类实例都有对应的Class
对象。类对象是由Java虚拟机(JVM)自动构造的。bootstrap
Class
类的方法常常在反射时被调用。数组
有三种方法能够建立Class对象socket
Class.forName(“className”)
:由于Class
类没有公共的构造方法,因此存在一个静态的方法返回Class
对象,即Class.forName()
用于建立Class
对象。要建立的Class
对象的类名在运行时肯定,不存在则抛出ClassNotFoundException
。(注意className
为类的完整包名)Class.forName("java.lang.String")
复制代码
Myclass.class
:当咱们在类名后面跟上.class
时,就会返回当前类的Class
对象。它主要应用于原始数据类型,而且仅在咱们知道类的名称时才使用。要建立的Class
对象的类名在编译时肯定Class c2 = String.class;
复制代码
请注意,此方法与类名一块儿使用,而不是与类实例一块儿使用函数
A a = new A(); // Class A 的实例a
Class c = A.class; // 正确用法
Class c = a.class; //编译出错
复制代码
obj.getClass()
: 此方法存在时Object
类中,它返回此obj
对象的运行时类。String str = new String("string");
Class c3 = str.getClass();
复制代码
此方法将Class
对象转换为字符串。它返回字符串表示形式,即字符串“class”或“interface”,后跟空格,而后是类的含包名名称。若是Class
对象表示基本类型,则此方法返回基本类型的名称,若是它表示void
,则返回“void”测试
描述:this
语法 :
public String toString() 参数 : NA 返回 : a string representation of this class object. 重写 : toString in class Object 复制代码
测试类:url
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());
}
}
复制代码
输出:spa
Class represented by c1: class java.lang.String
Class represented by c2: int
Class represented by c3: void
复制代码
返回描述此类的字符串,包括有关修饰符和类型参数的信息。code
描述:
语法 :
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
复制代码
返回与给定字符串名称的类或接口相关联的 类对象。
描述:
语法 :
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");
}
}
复制代码
输出:
复制代码
使用给定的类加载器返回与给定字符串名称的类或接口相关联的类对象。若是参数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)
}
}
复制代码
输出:
复制代码
此方法建立此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
复制代码
此方法肯定指定的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
复制代码
此方法肯定此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
复制代码
此方法肯定指定的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
复制代码
此方法肯定指定的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
复制代码
此方法肯定指定的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
复制代码
当且仅当此类是匿名类时,此方法才返回true。匿名类与本地类相似,只是它们没有名称
描述:
语法 :
public boolean isAnonymousClass() 参数 : NA 返回 : true if and only if this class is an anonymous class.false,otherwise. 复制代码
当且仅当此类是本地类时,此方法才返回true。本地类是在Java代码块中本地声明的类,而不是类的成员。
描述:
语法 :
public boolean isLocalClass() 参数 : NA 返回 : true if and only if this class is a local class.false,otherwise. 复制代码
当且仅当此类是Member类时,此方法返回true。
描述:
语法 :
public boolean isMemberClass() 参数 : NA 返回 : true if and only if this class is a Member class.false,otherwise. 复制代码
当且仅当此类在源代码中声明为枚举时,此方法才返回true
描述:
语法 :
public boolean isEnum() 参数 : NA 返回 : true iff this class was declared as an enum in the source code.false,otherwise. 复制代码
此方法肯定此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 。
描述:
语法 :
public String getName() 参数 : NA 返回 : returns the name of the name of the entity represented by this object. 复制代码
此方法返回源代码中给出的基础类的名称(不含包名)。若是基础类是匿名类,则返回空字符串
描述:
语法 :
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
复制代码
此方法返回此类的类加载器。若是类加载器是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对象数组,该对象表示由此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所表示的实体(类,接口,基本类型或void)的超类的Class。若是此Class表示Object类,接口,基本类型或void,则返回null。若是此对象表示数组类,则返回表示Object类的Class对象。
描述:
语法 :
public Class<? super T> getSuperclass()
参数 :
NA
返回 :
the superclass of the class represented by this object 复制代码
此方法返回表示此Class所表示的实体(类,接口,基本类型或void)的直接超类的Type。若是此Class表示Object类,接口,基本类型或void,则返回null。若是此对象表示数组类,则返回表示Object类的Class对象。
描述:
语法 :
public Type getGenericSuperclass() 参数 : NA 返回 : athe superclass of the class represented by this object 复制代码
此方法返回由此对象表示的类或接口实现的接口。若是此对象表示不实现接口的类或接口,则该方法返回长度为0的数组。若是此对象表示基本类型或void,则该方法返回长度为0的数组。
描述:
语法 :
public Class<?>[] getInterfaces()
参数 :
NA
返回 :
an array of interfaces implemented by this class. 复制代码
此方法返回此类的包。
描述:
语法 :
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对象数组,该对象反映此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对象数组,这些对象反映了类或接口的全部可访问的公共方法,以及今后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对象数组,这些对象反映此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对象,该对象反映此Class对象所表示的类或接口的指定公共成员字段
描述:
语法 :
public Field getField(String fieldName) throws NoSuchFieldException,SecurityException 参数 : fieldName - the field name 返回 : the Field object of this class specified by name 复制代码
此方法返回一个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对象,该对象反映此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
复制代码
此方法用于将对象强制转换为此Class对象表示的类或接口。
描述:
语法 :
public T cast(Object obj) 参数 : obj - the object to be cast 返回 : the object after casting, or null if obj is null 复制代码
此方法用于转换此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 复制代码