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

324
Views
Java: definición de un método genérico dentro de una clase anónima

El siguiente código Java funciona bien.

 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); }

Si el método se cambia a su forma genérica, el programa falla.

 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); }

¿Por qué falla? ¿Cómo se pueden definir métodos genéricos dentro de una clase anónima?

Esta pregunta es para fines de aprendizaje.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

El borrado de T es Object , que no tiene setEnabled . Funciona si le das un límite de JComponent , que define setEnabled :

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

0

El genérico T no se deriva explícitamente de una clase o una interfaz. Por lo tanto, se deriva de Object y Object no tiene el método setEnabled() .

Si desea usar genérico, puede especificar un tipo base java.swing que tenga este método. Por ejemplo: 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); }
over 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!