简体   繁体   中英

Java Generic Method basics (reflection)

I am trying to correctly understand how to use generics. I have been searching on it all morning but I get confused when the tutorials start adding multiple generic values, or using very abstract terms which I am still wrestling with.

I am still learning so any general advice is welcome, but I would like to specifically figure out the syntax for the method returning the 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);
    }

    // HELP HERE!
    public static <T extends Vehicle> T buy(Class<T> type, int topSpeed) {

        // create a new dynamic class T . . . I am lost on syntax

        return null; // return the new class T. I am lost on the 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! I am 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 only go " + topSpeed + " miles per hour");
    }
}

Can someone point out how to tie together this generic method?

You can't generically call the new operator. What you can do is use reflection, under the assumption you know the constructor's parameters. For example, assuming every vehicle has a constructor which takes an 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 something more specific
        System.err.println("Can't create an instance");
        System.err.println(e);
        return null;
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM