How are Anonymous inner classes used in Java?

后端 未结 18 1366
孤独总比滥情好
孤独总比滥情好 2020-11-21 05:19

What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?

18条回答
  •  别跟我提以往
    2020-11-21 05:44

    Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:

    public interface F {
       B f(A a);
    }
    

    You can use this anonymously to create a first-class function in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:

    public static int larger(final List ns, final int i) {
      for (Integer n : ns)
         if (n > i)
            return n;
      return i;
    }
    

    And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:

    public static int smaller(final List ns, final int i) {
       for (Integer n : ns)
          if (n < i)
             return n;
       return i;
    }
    

    These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows:

    public static  T firstMatch(final List ts, final F f, T z) {
       for (T t : ts)
          if (f.f(t))
             return t;
       return z;
    }
    

    You can use an anonymous class to use the firstMatch method:

    F greaterThanTen = new F {
       Boolean f(final Integer n) {
          return n > 10;
       }
    };
    int moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x);
    

    This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See "Can Your Programming Language Do This" by Joel himself.

    A nice library for programming Java in this style: Functional Java.

提交回复
热议问题