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

279
Views
¿Es posible usar Class<?> con el nuevo conmutador Pattern-Matching?

Como parte de una investigación sobre los parámetros de un método, probé el nuevo Pattern Matching for switch (Preview) . Usando una condición tradicional, funciona perfectamente:

 Method firstMethod = BitSet.class.getDeclaredMethods()[0]; Parameter firstParameter = firstMethod.getParameters()[0]; if (firstParameter.getType() == Integer.class) { System.out.println("Integer"); }

Cuando traté de refactorizarlo para usar una declaración de switch , no se compiló:

 Method firstMethod = BitSet.class.getDeclaredMethods()[0]; Parameter firstParameter = firstMethod.getParameters()[0]; switch (firstParameter.getType()) { case Integer.class: System.out.println("Integer"); case int.class: System.out.println("int"); default: System.out.println("other"); }

el error es:

 error: incompatible types: Class<Integer> cannot be converted to Class<CAP#1> case Integer.class: System.out.println("Integer"); ^ where CAP#1 is a fresh type-variable: CAP#1 extends Object from capture of ?

¿Es esto algo que no se puede hacer, o es solo un error de sintaxis?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Así no es como funciona el cambio de tipos. Puede cambiar el tipo real de un objeto y debe especificar nombres de tipo, en lugar de literales de Class .

 Object o = 42; switch(o) { case Integer i: System.out.println("Integer " + i); break; case String s: System.out.println("String " + s); break; default: System.out.println("other"); }

Tenga en cuenta que con la coincidencia de patrones, no hay compatibilidad con fallos, por lo que es obligatorio especificar la break . O usa la nueva sintaxis que no tiene fallas en primer lugar

 Object o = 42; switch(o) { case Integer i -> System.out.println("Integer " + i); case String s -> System.out.println("String " + s); default -> System.out.println("other"); }

El objeto devuelto por getType() siempre es una instancia de java.lang.Class , por lo que la bifurcación por su tipo no tiene sentido. Esto no significa que comparar los valores reales con una declaración o expresión de switch fuera imposible. La comparación se puede realizar con un patrón guardado:

 Method firstMethodWithParam = Arrays.stream(BitSet.class.getDeclaredMethods()) .filter(m -> m.getParameterCount() > 0) .findAny().orElseThrow(); switch(firstMethodWithParam.getParameterTypes()[0]) { case Class<?> cl && cl == Integer.class -> System.out.println("Integer"); case Class<?> cl && cl == int.class -> System.out.println("int"); case Class<?> cl && cl == String.class -> System.out.println("String"); case Class<?> cl && cl == long.class -> System.out.println("long"); case Class<?> cl && BitSet.class.isAssignableFrom(cl) -> System.out.println("BitSet or subtype"); default -> System.out.println("other"); }

pero eso es sólo para completar. Creo que es obvio que esto no es una mejora sobre las declaraciones if o un mapa de Class to handler.

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!