Java中如何使用匿名内部类?

发布于 2024-07-09 17:30:17 字数 44 浏览 6 评论 0 原文

Java中匿名类有什么用? 我们可以说使用匿名类是Java的优点之一吗?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

阳光①夏 2024-07-16 17:30:18

这里似乎没有人提到,但您也可以使用匿名类来保存泛型类型参数(通常由于类型擦除而丢失)

public abstract class TypeHolder<T> {
    private final Type type;

    public TypeReference() {
        // you may do do additional sanity checks here
        final Type superClass = getClass().getGenericSuperclass();
        this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
    }

    public final Type getType() {
        return this.type;
    }
}

如果您以匿名方式实例化此类

TypeHolder<List<String>, Map<Ineger, Long>> holder = 
    new TypeHolder<List<String>, Map<Ineger, Long>>() {};

,那么这样的 holder< /code> 实例将包含传递类型的非擦除定义。

用法

这对于构建验证器/反序列化器非常方便。 您还可以使用反射实例化泛型类型(因此,如果您想在参数化类型中执行 new T() - 欢迎您!)。

缺点/限制

  1. 您应该显式传递通用参数。 如果不这样做将导致类型参数丢失
  2. 每个实例化都会花费编译器生成额外的类,从而导致类路径污染/jar 膨胀

Seems nobody mentioned here but you can also use anonymous class to hold generic type argument (which normally lost due to type erasure):

public abstract class TypeHolder<T> {
    private final Type type;

    public TypeReference() {
        // you may do do additional sanity checks here
        final Type superClass = getClass().getGenericSuperclass();
        this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
    }

    public final Type getType() {
        return this.type;
    }
}

If you'll instantiate this class in anonymous way

TypeHolder<List<String>, Map<Ineger, Long>> holder = 
    new TypeHolder<List<String>, Map<Ineger, Long>>() {};

then such holder instance will contain non-erasured definition of passed type.

Usage

This is very handy for building validators/deserializators. Also you can instantiate generic type with reflection (so if you ever wanted to do new T() in parametrized type - you are welcome!).

Drawbacks/Limitations

  1. You should pass generic parameter explicitly. Failing to do so will lead to type parameter loss
  2. Each instantiation will cost you additional class to be generated by compiler which leads to classpath pollution/jar bloating
陌路黄昏 2024-07-16 17:30:18

匿名内部类用于创建永远不会再次引用的对象。 它没有名称,并且在同一语句中声明和创建。
这用在通常使用对象变量的地方。 您可以将变量替换为 new 关键字、对构造函数的调用以及 {} 中的类定义。

当用 Java 编写线程程序时,通常看起来像这样。

ThreadClass task = new ThreadClass();
Thread runner = new Thread(task);
runner.start();

这里使用的 ThreadClass 是用户定义的。 此类将实现创建线程所需的 Runnable 接口。 在 ThreadClass 中,还需要实现 run() 方法(仅在 Runnable 中的方法)。
很明显,摆脱 ThreadClass 会更有效,这正是匿名内部类存在的原因。

查看以下代码

Thread runner = new Thread(new Runnable() {
    public void run() {
        //Thread does it's work here
    }
});
runner.start();

此代码替换了最上面示例中对 task 的引用。 Thread() 构造函数内的匿名内部类没有使用单独的类,而是返回一个实现 Runnable 接口并覆盖 run()< 的未命名对象。 /代码> 方法。 run() 方法将包含执行线程所需工作的语句。

回答匿名内部类是否是Java的优点之一的问题时,我不得不说我不太确定,因为我目前对许多编程语言都不熟悉。 但我可以说的是,这绝对是一种更快、更简单的编码方法。

参考文献:Sams 《21 天自学 Java》第七版

An Anonymous Inner Class is used to create an object that will never be referenced again. It has no name and is declared and created in the same statement.
This is used where you would normally use an object's variable. You replace the variable with the new keyword, a call to a constructor and the class definition inside { and }.

When writing a Threaded Program in Java, it would usually look like this

ThreadClass task = new ThreadClass();
Thread runner = new Thread(task);
runner.start();

The ThreadClass used here would be user defined. This class will implement the Runnable interface which is required for creating threads. In the ThreadClass the run() method (only method in Runnable) needs to be implemented as well.
It is clear that getting rid of ThreadClass would be more efficient and that's exactly why Anonymous Inner Classes exist.

Look at the following code

Thread runner = new Thread(new Runnable() {
    public void run() {
        //Thread does it's work here
    }
});
runner.start();

This code replaces the reference made to task in the top most example. Rather than having a separate class, the Anonymous Inner Class inside the Thread() constructor returns an unnamed object that implements the Runnable interface and overrides the run() method. The method run() would include statements inside that do the work required by the thread.

Answering the question on whether Anonymous Inner Classes is one of the advantages of Java, I would have to say that I'm not quite sure as I am not familiar with many programming languages at the moment. But what I can say is it is definitely a quicker and easier method of coding.

References: Sams Teach Yourself Java in 21 Days Seventh Edition

没企图 2024-07-16 17:30:18

优化代码的最佳方法。 另外,我们可以用于类或接口的重写方法。

import java.util.Scanner;
abstract class AnonymousInner {
    abstract void sum();
}

class AnonymousInnerMain {
    public static void main(String []k){
        Scanner sn = new Scanner(System.in);
        System.out.println("Enter two vlaues");
            int a= Integer.parseInt(sn.nextLine());
            int b= Integer.parseInt(sn.nextLine()); 
        AnonymousInner ac = new AnonymousInner(){
            void sum(){
                int c= a+b;
                System.out.println("Sum of two number is: "+c);
            }
        };
        ac.sum();
    }

}

The best way to optimize code. also, We can use for an overriding method of a class or interface.

import java.util.Scanner;
abstract class AnonymousInner {
    abstract void sum();
}

class AnonymousInnerMain {
    public static void main(String []k){
        Scanner sn = new Scanner(System.in);
        System.out.println("Enter two vlaues");
            int a= Integer.parseInt(sn.nextLine());
            int b= Integer.parseInt(sn.nextLine()); 
        AnonymousInner ac = new AnonymousInner(){
            void sum(){
                int c= a+b;
                System.out.println("Sum of two number is: "+c);
            }
        };
        ac.sum();
    }

}
童话里做英雄 2024-07-16 17:30:18

还有一个优势:
如您所知,Java 不支持多重继承,因此,如果您使用“Thread”类作为匿名类,那么该类仍然留有一个空间供任何其他类扩展。

One more advantage:
As you know that Java doesn't support multiple inheritance, so if you use "Thread" kinda class as anonymous class then the class still has one space left for any other class to extend.

偏爱自由 2024-07-16 17:30:18

我发现 该问题的答案(重复) 是对于这个问题的回答非常简洁。

这是我的笔记。

对于一个用例:

Type type = new TypeToken>(){}.getType(); 
  

它等同于:

class MyTypeToken extends TypeToken>;   { } 
  TypeToken<集合<数据>>   tcd = new MyTypeToken(); 
  类型类型 = tcd.getType(); 
  

更简洁的简写:

类型类型 = 
      new TypeToken>() { // 这将初始化一个匿名对象 
          /* 在这里你可以重写方法并根据需要添加你自己的方法 */ 

      } /* 这结束了对象的初始化。  
             至此,匿名类就被创建并初始化了。   */ 

      .getType();   // 这里调用对象的方法 
  

与...一样:

TypeToken<集合<数据>>   tt = new TypeToken<集合<数据>>(){ }; 
  类型类型 = tt.getType(); 
  

和 ...

我还想提一下,匿名类与从同一父类继承的其他匿名类不具有相同的类类型。

如果您有以下情况:

TypeToken<集合<数据>>   tt1 = new TypeToken<集合<数据>>(){ }; 
  TypeToken<集合<数据>>   tt2 = new TypeToken<集合<数据>>(){ }; 
  

tt1.getClass() == tt2.getClass()永远为真。

这就是关于 java 中的匿名子类的所有要点。

I found that answer with its question (which is duplicated) is a very terse reply for this question.

Here are my notes.

For a use case:

Type type = new TypeToken<Collection<Data>>(){}.getType();

It's same as:

class MyTypeToken extends TypeToken<Collection<Data>> { }
TypeToken<Collection<Data>> tcd = new MyTypeToken();
Type type = tcd.getType();

More succinct shorthand:

Type type =
    new TypeToken<Collection<Data>>() { // this will initialise an anonymous object
        /* in here you can override methods and add your own if you need to */

    }   /* this ends the initialisation of the object. 
           At this point the anonymous class is created and initialised. */

    .getType(); // here you call a method on the object

same as:

TypeToken<Collection<Data>> tt = new TypeToken<Collection<Data>>(){ };
Type type = tt.getType();

And ...

One more thing I want to mention is that anonymous classes do not have the same class type as other anonymous classes which inherit from the same parent.

So if you have the following:

TypeToken<Collection<Data>> tt1 = new TypeToken<Collection<Data>>(){ };
TypeToken<Collection<Data>> tt2 = new TypeToken<Collection<Data>>(){ };

tt1.getClass() == tt2.getClass() will never be true.

And that's all important points about the anonymous subclass mean in java.

戏剧牡丹亭 2024-07-16 17:30:17

通过“匿名类”,我认为你的意思是 匿名内部类

当使用某些“额外”(例如重写方法)创建对象实例时,匿名内部类会很有用,而不必实际子类化一个类。

我倾向于使用它作为附加事件侦听器的快捷方式:

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // do something
    }
});

使用此方法可以使编码更快一些,因为我不需要创建一个实现 ActionListener 的额外类 - 我可以实例化一个匿名内部类,而不实际创建一个单独的类。

我只将这种技术用于“快速而肮脏”的任务,在这些任务中,让整个班级感觉没有必要。 拥有多个执行完全相同操作的匿名内部类应该重构为实际的类,无论是内部类还是单独的类。

By an "anonymous class", I take it you mean anonymous inner class.

An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.

I tend to use it as a shortcut for attaching an event listener:

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // do something
    }
});

Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener -- I can just instantiate an anonymous inner class without actually making a separate class.

I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.

淡写薰衣草的香 2024-07-16 17:30:17

匿名内部类实际上是闭包,因此它们可用于模拟 lambda 表达式或“委托”。 例如,采用此接口:

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

您可以匿名使用此接口来创建一流函数在爪哇。 假设您有以下方法,它返回给定列表中第一个大于 i 的数字,如果没有数字更大,则返回 i:

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

然后您还有另一个方法,返回给定列表中第一个小于 i 的数字,如果没有则返回 i没有更小的数字:

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

这些方法几乎相同。 使用第一类函数类型 F,我们可以将它们重写为一个方法,如下所示:

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

您可以使用匿名类来使用 firstMatch 方法:

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

这是一个非常人为的示例,但很容易看出能够传递函数就好像它们是值一样是一个非常有用的功能。 请参阅 Joel 本人的“你的编程语言能做到这一点吗”

一个很好的库,用于以这种风格进行 Java 编程:Functional Java。

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<A, B> {
   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<Integer> 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<Integer> 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> T firstMatch(final List<T> ts, final F<T, Boolean> 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<Integer, Boolean> greaterThanTen = new F<Integer, Boolean> {
   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.

じее 2024-07-16 17:30:17

匿名内部类用于以下场景:

1.) 对于覆盖(子类化),当类定义除当前情况外不可用时:

class A{
    public void methodA() {
        System.out.println("methodA");
    }
}

class B{
    A a = new A() {
        public void methodA() {
            System.out.println("anonymous methodA");
        }
    };
}

2.) 对于实现接口,当仅在当前情况下需要实现接口时:

interface InterfaceA{
    public void methodA();
}

class B{
    InterfaceA a = new InterfaceA() {
        public void methodA() {
            System.out.println("anonymous methodA implementer");
        }
    };
}

3.)参数定义匿名内部类:

interface Foo {
    void methodFoo();
}

class B{
    void do(Foo f) { }
}

class A{
    void methodA() {
        B b = new B();
        b.do(new Foo() {
            public void methodFoo() {
                System.out.println("methodFoo");
            } 
        });
    } 
} 

Anonymous inner class is used in following scenario:

1.) For Overriding(subclassing), when class definition is not usable except current case:

class A{
    public void methodA() {
        System.out.println("methodA");
    }
}

class B{
    A a = new A() {
        public void methodA() {
            System.out.println("anonymous methodA");
        }
    };
}

2.) For implementing an interface, when implementation of interface is required only for current case:

interface InterfaceA{
    public void methodA();
}

class B{
    InterfaceA a = new InterfaceA() {
        public void methodA() {
            System.out.println("anonymous methodA implementer");
        }
    };
}

3.) Argument Defined Anonymous inner class:

interface Foo {
    void methodFoo();
}

class B{
    void do(Foo f) { }
}

class A{
    void methodA() {
        B b = new B();
        b.do(new Foo() {
            public void methodFoo() {
                System.out.println("methodFoo");
            } 
        });
    } 
} 
昵称有卵用 2024-07-16 17:30:17

我有时使用它们作为 Map 实例化的语法技巧:

Map map = new HashMap() {{
   put("key", "value");
}};

vs

Map map = new HashMap();
map.put("key", "value");

在执行大量 put 语句时它可以节省一些冗余。 但是,当外部类需要通过远程处理进行序列化时,我在执行此操作时也遇到了问题。

I use them sometimes as a syntax hack for Map instantiation:

Map map = new HashMap() {{
   put("key", "value");
}};

vs

Map map = new HashMap();
map.put("key", "value");

It saves some redundancy when doing a lot of put statements. However, I have also run into problems doing this when the outer class needs to be serialized via remoting.

本宫微胖 2024-07-16 17:30:17

它们通常用作回调的详细形式。

我想你可以说与没有它们相比,它们是一个优势,并且每次都必须创建一个命名类,但是类似的概念在其他语言中实现得更好(作为闭包或块)

这是一个摇摆示例

myButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        // do stuff here...
    }
});

虽然它仍然很混乱冗长,这比强迫您为每个丢弃的侦听器定义一个命名类要好得多(尽管根据情况和重用,这可能仍然是更好的方法)

They're commonly used as a verbose form of callback.

I suppose you could say they're an advantage compared to not having them, and having to create a named class every time, but similar concepts are implemented much better in other languages (as closures or blocks)

Here's a swing example

myButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        // do stuff here...
    }
});

Although it's still messily verbose, it's a lot better than forcing you to define a named class for every throw away listener like this (although depending on the situation and reuse, that may still be the better approach)

云朵有点甜 2024-07-16 17:30:17

您可以在需要在另一个函数中创建一个用于特定目的的类的情况下使用它,例如,作为侦听器、作为可运行对象(以生成线程)等。

其想法是从代码内部调用它们一个函数,这样您就永远不会在其他地方引用它们,因此您不需要命名它们。 编译器只是枚举它们。

它们本质上是语法糖,随着它们变大,通常应该转移到其他地方。

我不确定这是否是 Java 的优点之一,但如果您确实使用它们(不幸的是,我们都经常使用它们),那么您可以说它们就是其中之一。

You use it in situations where you need to create a class for a specific purpose inside another function, e.g., as a listener, as a runnable (to spawn a thread), etc.

The idea is that you call them from inside the code of a function so you never refer to them elsewhere, so you don't need to name them. The compiler just enumerates them.

They are essentially syntactic sugar, and should generally be moved elsewhere as they grow bigger.

I'm not sure if it is one of the advantages of Java, though if you do use them (and we all frequently use them, unfortunately), then you could argue that they are one.

走过海棠暮 2024-07-16 17:30:17

匿名类指南。

  1. 匿名类同时声明和初始化。

  2. 匿名类必须扩展或实现一个且仅一个类或接口。

  3. 由于匿名类没有名称,因此只能使用一次。

例如:

button.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub

    }
});

GuideLines for Anonymous Class.

  1. Anonymous class is declared and initialized simultaneously.

  2. Anonymous class must extend or implement to one and only one class or interface resp.

  3. As anonymouse class has no name, it can be used only once.

eg:

button.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub

    }
});
等待圉鍢 2024-07-16 17:30:17

是的,匿名内部类绝对是Java的优点之一。

使用匿名内部类,您可以访问周围类的最终变量和成员变量,这在侦听器等中派上用场。

但一个主要优点是内部类代码(至少应该)与周围的类/方法/块,具有特定的上下文(周围的类、方法和块)。

Yes, anonymous inner classes is definitely one of the advantages of Java.

With an anonymous inner class you have access to final and member variables of the surrounding class, and that comes in handy in listeners etc.

But a major advantage is that the inner class code, which is (at least should be) tightly coupled to the surrounding class/method/block, has a specific context (the surrounding class, method, and block).

双马尾 2024-07-16 17:30:17
new Thread() {
        public void run() {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                System.out.println("Exception message: " + e.getMessage());
                System.out.println("Exception cause: " + e.getCause());
            }
        }
    }.start();

这也是使用线程的匿名内部类型的示例之一

new Thread() {
        public void run() {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                System.out.println("Exception message: " + e.getMessage());
                System.out.println("Exception cause: " + e.getCause());
            }
        }
    }.start();

This is also one of the example for anonymous inner type using thread

分分钟 2024-07-16 17:30:17

内部类与外部类的实例关联有两种特殊类型:本地类和匿名类 。 匿名类使我们能够同时声明和实例化一个类,从而使代码简洁。 当我们只需要一次本地类时,我们会使用它们,因为它们没有名称。

考虑 doc 中的示例,其中我们有一个 Person 类:

public class Person {

    public enum Sex {
        MALE, FEMALE
    }

    String name;
    LocalDate birthday;
    Sex gender;
    String emailAddress;

    public int getAge() {
        // ...
    }

    public void printPerson() {
        // ...
    }
}

我们有一个方法来打印与搜索条件匹配的成员,如下所示:

public static void printPersons(
    List<Person> roster, CheckPerson tester) {
    for (Person p : roster) {
        if (tester.test(p)) {
            p.printPerson();
        }
    }
}

其中 CheckPerson 是一个接口,如下所示:

interface CheckPerson {
    boolean test(Person p);
}

现在我们可以利用实现此接口的匿名类来指定搜索标准为:

printPersons(
    roster,
    new CheckPerson() {
        public boolean test(Person p) {
            return p.getGender() == Person.Sex.MALE
                && p.getAge() >= 18
                && p.getAge() <= 25;
        }
    }
);

这里的接口非常简单,匿名类的语法似乎笨拙且不清楚。

Java 8引入了一个术语函数式接口这是一个只有一个抽象方法的接口,因此我们可以说CheckPerson是一个函数式接口。 我们可以利用 Lambda 表达式 它允许我们通过函数作为方法参数为:

printPersons(
                roster,
                (Person p) -> p.getGender() == Person.Sex.MALE
                        && p.getAge() >= 18
                        && p.getAge() <= 25
        );

我们可以使用标准函数接口Predicate来代替接口CheckPerson,这将进一步减少所需的代码量。

An inner class is associated with an instance of the outer class and there are two special kinds: Local class and Anonymous class. An anonymous class enables us to declare and instantiate a class at same time, hence makes the code concise. We use them when we need a local class only once as they don't have a name.

Consider the example from doc where we have a Person class:

public class Person {

    public enum Sex {
        MALE, FEMALE
    }

    String name;
    LocalDate birthday;
    Sex gender;
    String emailAddress;

    public int getAge() {
        // ...
    }

    public void printPerson() {
        // ...
    }
}

and we have a method to print members that match search criteria as:

public static void printPersons(
    List<Person> roster, CheckPerson tester) {
    for (Person p : roster) {
        if (tester.test(p)) {
            p.printPerson();
        }
    }
}

where CheckPerson is an interface like:

interface CheckPerson {
    boolean test(Person p);
}

Now we can make use of anonymous class which implements this interface to specify search criteria as:

printPersons(
    roster,
    new CheckPerson() {
        public boolean test(Person p) {
            return p.getGender() == Person.Sex.MALE
                && p.getAge() >= 18
                && p.getAge() <= 25;
        }
    }
);

Here the interface is very simple and the syntax of anonymous class seems unwieldy and unclear.

Java 8 has introduced a term Functional Interface which is an interface with only one abstract method, hence we can say CheckPerson is a functional interface. We can make use of Lambda Expression which allows us to pass the function as method argument as:

printPersons(
                roster,
                (Person p) -> p.getGender() == Person.Sex.MALE
                        && p.getAge() >= 18
                        && p.getAge() <= 25
        );

We can use a standard functional interface Predicate in place of the interface CheckPerson, which will further reduce the amount of code required.

爱的十字路口 2024-07-16 17:30:17

我使用匿名对象来调用新线程..

new Thread(new Runnable() {
    public void run() {
        // you code
    }
}).start();

i use anonymous objects for calling new Threads..

new Thread(new Runnable() {
    public void run() {
        // you code
    }
}).start();
不一样的天空 2024-07-16 17:30:17

匿名内部类在为不同对象提供不同实现时可能很有用。 但应该非常谨慎地使用,因为它会给程序可读性带来问题。

Anonymous inner class can be beneficial while giving different implementations for different objects. But should be used very sparingly as it creates problem for program readability.

她说她爱他 2024-07-16 17:30:17

匿名类在类终结中的主要用法之一称为终结器守护者。 在 Java 世界中,应该避免使用 Finalize 方法,直到真正需要它们为止。 你必须记住,当你重写子类的finalize方法时,你应该总是调用super.finalize(),因为超类的finalize方法不会自动调用,你可以遇到内存泄漏问题。

因此,考虑到上述事实,您可以使用匿名类,例如:

public class HeavyClass{
    private final Object finalizerGuardian = new Object() {
        @Override
        protected void finalize() throws Throwable{
            //Finalize outer HeavyClass object
        }
    };
}

使用这种技术,您可以减轻自己和其他开发人员在 的每个子类上调用 super.finalize() 的负担。 HeavyClass 需要 Finalize 方法。

One of the major usage of anonymous classes in class-finalization which called finalizer guardian. In Java world using the finalize methods should be avoided until you really need them. You have to remember, when you override the finalize method for sub-classes, you should always invoke super.finalize() as well, because the finalize method of super class won't invoke automatically and you can have trouble with memory leaks.

so considering the fact mentioned above, you can just use the anonymous classes like:

public class HeavyClass{
    private final Object finalizerGuardian = new Object() {
        @Override
        protected void finalize() throws Throwable{
            //Finalize outer HeavyClass object
        }
    };
}

Using this technique you relieved yourself and your other developers to call super.finalize() on each sub-class of the HeavyClass which needs finalize method.

安稳善良 2024-07-16 17:30:17

您可以通过这种方式使用匿名类

TreeSet treeSetObj = new TreeSet(new Comparator()
{
    public int compare(String i1,String i2)
    {
        return i2.compareTo(i1);
    }
});

You can use anonymous class this way

TreeSet treeSetObj = new TreeSet(new Comparator()
{
    public int compare(String i1,String i2)
    {
        return i2.compareTo(i1);
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文