Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Defining a generic method inside an anonymous class

The following java code works fine.

public static void main(String[] arg){
    JPanel p = (new JPanel());
    p.add( new Object(){
        JButton f(JButton x){
            x.setEnabled(false);
            return x;
        }}.f(new JButton("B")) );
    JFrame w = new JFrame("W");
    w.add(p);
    w.pack();
    w.setVisible(true);
}

If the method is changed to its generic form the program fails.

public static void main(String[] arg){
    JPanel p = (new JPanel());
    p.add( new Object(){
        <T> T f(T x){
            x.setEnabled(false);
            return x;
        }}.f(new JButton("B")) );
    JFrame w = new JFrame("W");
    w.add(p);
    w.pack();
    w.setVisible(true);
}

Why does it fail? How can you define generic methods within an anonymous class?

This question is for learning purposes.

like image 483
user7841452 Avatar asked Apr 09 '17 18:04

user7841452


People also ask

Can we create a generic method inside a non generic class?

Yes, you can define a generic method in a non-generic class in Java.

Can anonymous class have multiple methods?

Because the EventHandler<ActionEvent> interface contains only one method, you can use a lambda expression instead of an anonymous class expression. See the section Lambda Expressions for more information. Anonymous classes are ideal for implementing an interface that contains two or more methods.

Can an anonymous class implement an interface in Java?

A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time. A regular class can extend a class and implement any number of interfaces simultaneously. But anonymous Inner class can extend a class or can implement an interface but not both at a time.


1 Answers

T's erasure is Object, which does not have setEnabled. It works if you give it a bound of JComponent, which definessetEnabled:

public static void main(String[] arg) {
    JPanel p = (new JPanel());
    p.add( new Object(){
        <T extends JComponent> T f(T x){
            x.setEnabled(false);
            return x;
        }}.f(new JButton("B")) );
    JFrame w = new JFrame("W");
    w.add(p);
    w.pack();
    w.setVisible(true);
}
like image 77
Jorn Vernee Avatar answered Nov 04 '22 06:11

Jorn Vernee