zoukankan      html  css  js  c++  java
  • 匿名内部类 Inner class

    先说结论

    匿名内部类分两种,一种是接口的匿名实现,一种是类的匿名子类!后者往往用于修改特定方法。

    再说起因

    本来以为匿名内部类很简单,就是接口的匿名实现,直到我发现了下面这段代码:

     1 public class FooBeanInfo extends SimpleBeanInfo {
     2 
     3     public PropertyDescriptor[] getPropertyDescriptors() {
     4         try {
     5             final PropertyEditor numberPE = new CustomNumberEditor(Integer.class, true);
     6             PropertyDescriptor ageDescriptor = new PropertyDescriptor("age", Foo.class) {
     7                 public PropertyEditor createPropertyEditor(Object bean) {
     8                     return numberPE;
     9                 };
    10             };
    11             return new PropertyDescriptor[] { ageDescriptor };
    12         }
    13         catch (IntrospectionException ex) {
    14             throw new Error(ex.toString());
    15         }
    16     }
    17 }
    View Code

    注意第6行到第10行之间的代码。

    开始以为PropertyDescriptor是一个接口,结果不是,这就是一个正常的类。懵比。。WTF!!!

    好在几分钟内就转过来了,这个似乎可能好像也是内部类吧?

    二话不说,先验证一番:

    先来一个类:

     1 package inherit;
     2 
     3 /**
     4  * @author LarryZeal
     5  *
     6  */
     7 public class Editor {
     8 
     9     public void hello() {
    10         System.out.println("hello from Editor");
    11     }
    12 }

    再来个测试:

     1 package inherit;
     2 
     3 import org.junit.Test;
     4 
     5 /**
     6  * @author LarryZeal
     7  *
     8  */
     9 public class InheritFromEditorTest {
    10 
    11     /**
    12      * 对接口来说是匿名实现,对类来说就是匿名子类了。
    13      */
    14     @Test
    15     public void run() {
    16         Editor editor = new Editor() {
    17             public void hello() {
    18                 System.out.println("what!!!");
    19             }
    20         };
    21 
    22         editor.hello();
    23     }
    24 }

    运行,结果输出"what!!!",验证通过,果然如此。

    再说下用途

    匿名子类往往用于重写特定的方法。

    补充

    根据某群内 随意丶nice 童鞋的提示,还有更进一步的用法:

     1 @Test
     2 public void run2() {
     3     Map<String, String> map = new HashMap<String, String>() {
     4         {
     5             put("1", "1");
     6             put("2", "2");
     7             put("3", "3");
     8             put("4", "4");
     9             put("5", "5");
    10             // ...
    11         }
    12     };
    13 }

    利用匿名子类的构造代码块执行某些特定操作,还不需要使用对象的引用!省时省力哦!

  • 相关阅读:
    1003 Dijkstra算法
    微信公众号签名错误(invalid signature)的问题排查
    使用OpenSSL(Windows x64版)将pem格式证书转换为p12格式
    单篇文章JS模拟分页
    自制Javascript分页插件,支持AJAX加载和URL带参跳转两种初始化方式,可用于同一页面的多个分页和不同页面的调用
    仿写Windows7桌面和任务栏 HTML5+CSS3+Jquery实现
    【转载】ASP.NET线程安全与静态变量的生命周期浅谈
    ASP.NET 多线程 监控任务执行情况,并显示进度条
    再谈Cookies欺骗
    Cookies欺骗分析与防护
  • 原文地址:https://www.cnblogs.com/larryzeal/p/5949821.html
Copyright © 2011-2022 走看看