java - Calling Enum.values() on a generic type -


the goal implement generic enum translator. know enum1 , enum2 have same values , in same order.

the goal implement this:(this works)

private static enum1 translateenum(enum2 originalenum) {     return enum1.values()[originalenum.ordinal()]; } 

but have several enums, want make generic method: (this doesn't work)

private static < t extends enum<t>,g extends enum<g>> t translateenum(g originalenum) {     return t.values()[originalenum.ordinal()];         } 

my problem @ t.values() compiler tells me :

the method values() undefined type t

do guys have idea of how solve issue or have alternative idea problem?

a common way pass target class object (or object of target class) argument function, use methods class object tricky part. enum classes, class object has a method returns equivalent of enum.values(). can use enum values target class:

public class scratch {     enum lower { a, b, c };     enum upper { a, b, c };      static <t extends enum<t>> t translate(enum<?> afrom, class<t> ato) {         return ato.getenumconstants()[afrom.ordinal()];     }      public static void main(string[] args) {         (lower ll : lower.values()) {             upper uu = translate(ll, upper.class);             system.out.printf("upper of '%s' '%s'\n", ll, uu);         }         (upper uu : upper.values()) {             lower ll = translate(uu, lower.class);             system.out.printf("lower of '%s' '%s'\n", uu, ll);         }     } } 

running produces following output:

upper of 'a' 'a' upper of 'b' 'b' upper of 'c' 'c' lower of 'a' 'a' lower of 'b' 'b' lower of 'c' 'c' 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -