简体   繁体   English

新的Foo(bar)是什么{public void baz(){…}}; 在Java中意味着什么?

[英]What does new Foo(bar) {public void baz(){…} }; mean in Java?

I'm trying to understand the NavigationDrawer sample for the Android SDK and I met this: 我试图了解Android SDK的NavigationDrawer示例,并且遇到了这个问题:

 ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
            this,                  /* host Activity */
            mDrawerLayout,         /* DrawerLayout object */
            R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open,  /* "open drawer" description for accessibility */
            R.string.drawer_close  /* "close drawer" description for accessibility */
            ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };

When do these methods get called, right after the instantiation? 实例化之后,何时调用这些方法? I'm not familiar with this syntax. 我对这种语法不熟悉。 How does this work? 这是如何运作的? Thanks 谢谢

This is an anonymous inner class. 这是一个匿名内部类。 Given an interface or class Foo with 0 or more abstract methods, you can use: 给定具有0个或更多个抽象方法的接口或类Foo,可以使用:

Foo blech=new Foo(){
    void bar(int baz){
        System.out.println("quux");
    }
}

to create an instance of Foo with methods implemented or overridden. 用实现或重写的方法创建Foo实例。 All abstract methods(of which there may be 0) will need to be implemented in the braces. 所有抽象方法(可能有0个)都需要在花括号中实现。 The constructor is still called as usual and parameters can be passed in the parentheses. 仍然照常调用构造函数,并且可以在括号中传递参数。

These are often used for listeners or other objects that need to be run and should specify different actions without creating new classes extending or implementing them. 它们通常用于侦听器或需要运行的其他对象,并且应指定不同的操作,而无需创建扩展或实现它们的新类。

These will compile down to [Outer Class]$[Number].class , once for each anonymous inner class used in the code, even if any are never reached or any are used multiple times 这些将编译为[Outer Class]$[Number].class ,对于代码中使用的每个匿名内部类而言,一次编译一次,即使从未达到或多次使用过

It is possible to override methods of a class for one specific instance by using that syntax. 通过使用该语法,可以为一个特定实例覆盖类的方法。 A very common usage is indeed Listeners or Handlers (eg: MouseListener, KeyListener, etc...). 实际上,非常常见的用法是侦听器或处理程序(例如:MouseListener,KeyListener等)。

This results in an anonymous subclass of the class you are extending. 这将导致您扩展的类的匿名子类。 The subclass has no name. 子类没有名称。 And is compiled into WrapperClass$0 , WrapperClass$1 and so on... 并被编译为WrapperClass$0WrapperClass$1等...

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

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