关于Test.class和new Test().getClass()的区别

链接: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:如果该类型是一个数组,那么返回该数组的组件类型。
        
    }
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值