Java的getClass()

我们都知道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 {private Class clazz;public DaoSupportImpl() {ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); // 这才是DaoSupportImplthis.clazz = (Class) pt.getActualTypeArguments()[0]; }




本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部