简体   繁体   English

匿名类的对象类型是什么

[英]What is the object type of an anonymous class

Please look at the Java classes below: 请查看下面的Java类:

 class A {
   public void doProcess(){
      System.out.println("Process from A class!");
   }
 }

 class B extends A {
   @Override
   public void doProcess(){
      System.out.println("Process from B class!");
   }
 }

I have 2 classes as shown above. 我有2个课程,如上所示。 If I were to do the below (an anonymous class) 如果我要做以下(匿名课程)

 new B() {
   @Override
   public void doProcess(){
      System.out.println("Process from Anonymous class");
   }        
 }

Am I creating new subclass of B? 我是否在创建B的新子类? Or is it an instance of B? 或者它是B的一个实例?

I know I could assign the anonymous implementation to either B or A. What I wasn't sure is on the instance of the anonymous class that's created. 我知道我可以将匿名实现分配给B或A.我不确定是在创建的匿名类的实例上。 More curios on what Java does than for any practical purposes. 更多关于Java所做的事情,而不是任何实际目的。 I don't know how to get the class object of this anonymous inner class to use some reflection API and figure that out myself. 我不知道如何让这个匿名内部类的类对象使用一些反射API并自己解决。

You are creating an instance of an anonymous sub-class of class B . 您正在创建B类的匿名子类的实例。

B b = new B() {
   @Override
   public void doProcess(){
      System.out.println("Process from Anonymous class");
   }        
}
System.out.println (b.getClass ().getSuperclass ());

This will print 这将打印

class some.package.B

where some.package is the package where class B is located. 其中some.package是B类所在的包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM