Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

313
Views
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.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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);
}
about 4 years ago · Santiago Trujillo Report

0

The T generic doesn't derive explicitly from a class or an interface. So it derives from Objectand Object has no setEnabled() method.

If you want to use generic, you could specify a java.swing base type that has this method. For example : javax.swing.AbstractButton.

public static void main(String[] arg){
    JPanel p = (new JPanel());
    p.add( new Object(){
        <T extends AbstractButton> 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);
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!