java - Typesafe cast in generic -


i have question around topic generics in java: let's have following generic (static) method in class. in method, want have access method/fields of real class. there typesafe way in static language java? or there workarounds?

public class genericclassutil {  public static <t> void  workwithrealtypeattr(t objectclass) { //here access values of easel, cat, dog or other class }  } 

in main code:

genericclassutil.workwithrealtypeattr(new easel()); genericclassutil.workwithrealtypeattr(new cat()); genericclassutil.workwithrealtypeattr(new dog()); 

create interface , extend easel, cat, dog class interface.

public static <t extends thatinterface>  workwithrealtypeattr(t objectclass) { //here access values of easel, cat, dog or other class } 

ref:

there may times when want restrict types can used type arguments in parameterized type. example, method operates on numbers might want accept instances of number or subclasses. bounded type parameters for.

to declare bounded type parameter, list type parameter's name, followed extends keyword, followed upper bound, in example number. note that, in context, extends used in general sense mean either "extends" (as in classes) or "implements" (as in interfaces).

public class box<t> {      private t t;                public void set(t t) {         this.t = t;     }      public t get() {         return t;     }      public <u extends number> void inspect(u u){         system.out.println("t: " + t.getclass().getname());         system.out.println("u: " + u.getclass().getname());     }      public static void main(string[] args) {         box<integer> integerbox = new box<integer>();         integerbox.set(new integer(10));         integerbox.inspect("some text"); // error: still string!     } } 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -