简体   繁体   English

Java中的匿名内部类及其语法

[英]Anonymous inner class in java and their syntax

I'm very new to Java and I'm attempting to write an android app and going through the facebook api. 我是Java的新手,正尝试编写一个android应用程序并通过facebook api。 I'm looking at this page , specifically, this 我正在看这个页面 ,特别是这个

    LoginManager.getInstance().registerCallback(callbackManager,
        new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                // App code
            }

            @Override
            public void onCancel() {
                 // App code
            }

            @Override
            public void onError(FacebookException exception) {
                 // App code   
            }
});

This work just fine, I'm just trying to understand how. 这项工作很好,我只是想了解如何做。 I'm not understanding the method in a method and more specifically, how would I extract this if I wanted to write it differently? 我不了解方法中的方法,更具体地说,如果我想以不同的方式编写它,该如何提取呢?

I tried creating another class 我尝试创建另一个课程

public class FaceBookCallbackLogin implements FacebookCallback<LoginResult> {



@Override
public void onSuccess(LoginResult loginResult) {
    ....
}

@Override
public void onCancel() {

}

and tried to initiate the login from my MainActivity 并尝试从我的MainActivity启动登录

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    callbackManager = CallbackManager.Factory.create();
    setContentView(R.layout.activity_main);
    info = (TextView)findViewById(R.id.info);
    loginButton = (LoginButton)findViewById(R.id.login_button);
    loginButton.setReadPermissions("email");

    loginButton.registerCallback(callbackManager, new FaceBookCallbackLogin());
}

but, this never calls the onSuccess method in FaceBookCallbackLogin, and I can't call it explicitly because I don't have the param LoginResult. 但是,它永远不会在FaceBookCallbackLogin中调用onSuccess方法,并且由于我没有参数LoginResult,所以无法显式调用它。

So, how would i write this so I can have the login in a different class? 因此,我将如何编写此代码,以便可以将登录名设置为其他类? In the original code, where is the param for onSuccess - LoginResult - coming from? 在原始代码中,onSuccess的参数-LoginResult-的来源是什么?

The way you have changed from anonymous inner class to separate class looks just fine. 从匿名内部类更改为单独类的方式看起来不错。

However, in first example you have done this: 但是,在第一个示例中,您已执行以下操作:

LoginManager.getInstance().registerCallback

In second example you have done this: 在第二个示例中,您已执行以下操作:

loginButton.registerCallback

Maybe that is the problem.. 也许就是这个问题。

Okay, So the Javadocs say 好的,所以Javadocs

"Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once". “匿名类使您的代码更简洁。它们使您可以同时声明和实例化一个类。它们类似于本地类,只是它们没有名称。如果需要使用本地类,请使用它们。只有一次”。

A benefit of the above is it allows you to be precise about your definition for a particular interface implementation without having to go through the hassle of creating new classes for each implementation. 上面的好处是它允许您精确定义特定接口实现的定义,而不必为每个实现创建新类的麻烦。 Look at the example below. 看下面的例子。

interface Foo {
    String saySomething(String something);
}

class Bar {

  public static void main(String [] args) {
      //I want this anonymous inner classes implementation to **uppercase** the strings
      Foo sayUppercase = new Foo() {
          @Override
          public String saySomething(String something) {
              return something.toUpperCase();
          }
      };
      sayUppercase.saySomething("Java");
      //output: JAVA

      Foo sayLowerCase = new Foo() {
          //I want this anonymous inner classes implementation to **lowercase** the strings
          @Override
          public String saySomething(String something) {
              return something.toLowerCase();
          }
       };
       sayLowerCase.saySomething("Java");
      //output: java
  }  
}

Notice how I am implementing the same saySomething method differently without having to create two separate classes (class files) for each implementation. 注意,我如何以不同的方式实现相同的saySomething方法,而不必为每个实现创建两个单独的类(类文件)。 I am almost inlining the implementation of the class. 我几乎要讲解该类的实现。

From an Android perspective this is very useful, imagine having to create a separate class for your click listeners. 从Android的角度来看,这非常有用,想象一下必须为您的点击监听器创建一个单独的类。 It is still possible, however it is much more simple and readable to create a simple anonymous inner-class for your implementation of your click-listener 仍然可能,但是为您的点击侦听器实现创建简单的匿名内部类更加简单易读

mLoginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Perform Action
        }
    });

Is much simpler to read and understand than creating a new class that implements View.OnClickListener like below 与创建实现如下所示的View.OnClickListener的新类相比,它易于阅读和理解。

public class LoginButtonOnClickListener implements View.OnClickListener {

    @Override
    public void onClick(View view) {
        //Perform action
    }
}

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

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