链接:oracle官方解释
package com.qimiguang.common;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class TestClass {
public static void main(String args[]) throws Exception{
Set s = new HashSet();
s.add("foo");
Iterator it = s.iterator();
Class[] argsClass = new Class[0];
Method m = Iterator.class.getMethod("hasNext",argsClass);
System.out.println(m.invoke(it,argsClass)); //true
Set s2 = new HashSet(); // HashSet底层是用HashMap实现的
s2.add("foo");
Iterator it2 = s2.iterator();
Class[] argsClass2 = new Class[0];
Method m2 = it2.getClass().getMethod("hasNext",argsClass2);
// System.out.println(m2.invoke(it2,argsClass2)); //报错!!!
System.out.println(m); // public abstract boolean java.util.Iterator.hasNext()
System.out.println(m2); // public final boolean java.util.HashMap$HashIterator.hasNext()
System.out.println(Iterator.class); //interface java.util.Iterator 可以这样理解 : Iterator.class是在编译器即决定的
System.out.println(it2.getClass()); //class java.util.HashMap$KeyIterator it2.getClass()是在运行期决定的,
//运行期it2指向的是new出来的HashMap$KeyIterator
Class c = String.class;
Class c2 = new String().getClass();
System.out.println(c); //class java.lang.String
System.out.println(c2); //class java.lang.String
System.out.println(c == c2); // true
// stackoverflow上的解释:
// a.getClass() returns the runtime type of a. I.e., if you have A a = new B(); then a.getClass() will return the B class.
// A.class evaluates to the A class statically, and is used for other purposes often related to reflection.
// They are actually different with regards to where you can use them. A.class works at compile time while a.getClass() requires an instance of
// type A and works at runtime.
// 获得Class对象后,可以执行以下操作
// getName():String:获得该类型的全称名称。
// getSuperClass():Class:获得该类型的直接父类,如果该类型没有直接父类,那么返回null。
// getInterfaces():Class[]:获得该类型实现的所有接口。
// isArray():boolean:判断该类型是否是数组。
// isEnum():boolean:判断该类型是否是枚举类型。
// isInterface():boolean:判断该类型是否是接口。
// isPrimitive():boolean:判断该类型是否是基本类型,即是否是int,boolean,double等等。
// isAssignableFrom(Class cls):boolean:判断这个类型是否是类型cls的父(祖先)类或父(祖先)接口。
// getComponentType():Class:如果该类型是一个数组,那么返回该数组的组件类型。
}
}