Java Generic Method basics (reflection) -
i trying correctly understand how use generics. have been searching on morning confused when tutorials start adding multiple generic values, or using abstract terms still wrestling with.
i still learning general advice welcome, figure out syntax method returning generic class.
for example consider:
public class genericsexample4 { public static void main(string args[]) { car car; truck truck; car = buy(car.class, 95); truck = buy(truck.class, 45); } // here! public static <t extends vehicle> t buy(class<t> type, int topspeed) { // create new dynamic class t . . . lost on syntax return null; // return new class t. lost on syntax here :( } } interface vehicle { public void floorit(); } class car implements vehicle { int topspeed; public car(int topspeed) { this.topspeed = topspeed; } @override public void floorit() { system.out.println("vroom! going " + topspeed + " miles per hour"); } } class truck implements vehicle { int topspeed; public truck(int topspeed) { this.topspeed = topspeed; } @override public void floorit() { system.out.println("i can go " + topspeed + " miles per hour"); } }
can point out how tie generic method?
you can't generically call new
operator. can use reflection, under assumption know constructor's parameters. example, assuming every vehicle has constructor takes int
top speed:
public static <t extends vehicle> t buy(class<t> type, int topspeed) { try { return type.getconstructor(integer.type).newinstance(topspeed); } catch (exception e) { // or more specific system.err.println("can't create instance"); system.err.println(e); return null; } }
Comments
Post a Comment