Java的getClass()

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huangzhilin2015/article/details/50126821

我们都知道Class是用来描述类的,在类的内部通过getClass方法得到的结果是当前类的全名。那如果在父类使用getClass,得到的是子类class还是父类class呢?

如下:

package com.hzl.test1;

public class TestPrint{
    private class Test1{
        private Test1(){
            System.out.println(this.getClass());
        }
    }
    public void test(){
        new Test1();
    }
    public static void main(String[] args) {
        TestPrint tp = new TestPrint();
        tp.test();
    }
}
输出为:class com.hzl.test1.TestPrint$test1,这是无可厚非。现在添加内部类Test2,让Test2继承Test1,在Test1构造器里输出getClass:

package com.hzl.test1;

public class TestPrint{
    
    private class Test1{
        private Test1(){
            System.out.println(this.getClass());
        }
    }
    private class Test2 extends Test1{
        
    }
    public void test(){
        new Test2();
    }
    public static void main(String[] args) {
        TestPrint tp = new TestPrint();
        tp.test();
    }
}

输出:class com.hzl.test1.TestPrint$Test2

发现,此时打印出的是子类的信息。说明this代表的都是当前new的对象。现在将Test1定义为抽象类

package com.hzl.test1;

public class TestPrint{
    
    private abstract class Test1{
        private Test1(){
            System.out.println(this.getClass());
        }
    }
    private class Test2 extends Test1{
        
    }
    public void test(){
        new Test2();
    }
    public static void main(String[] args) {
        TestPrint tp = new TestPrint();
        tp.test();
    }
}
正常打印:class com.hzl.test1.TestPrint$Test2

所以我们平时在开发时,抽象Dao层的时候,可能会有如下代码段

public abstract class DaoSupportImpl<T> {


	private Class<T> clazz;

	public DaoSupportImpl() {
		ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); // 这才是DaoSupportImpl
		this.clazz = (Class<T>) pt.getActualTypeArguments()[0]; 
		
	}



猜你喜欢

转载自blog.csdn.net/huangzhilin2015/article/details/50126821
今日推荐