Search code examples
javagenericsgeneric-method

Checking types in a generic method


I to know if it is possible to have an if statement in a method that will check the type of the generic used. In the case that got me thinking about this I want to handle a pretty basic Point2D class and a Point3D class differently. In the case of the 3D point I need to access Point3d.z, and I am not sure whether or not this will cause problems A pseudo code version of what I would like to do is

public <T> void processPoints(T point) {
    process(point.x);
    process(point.y);
    if (T == Point3D) { // What do I do here?
        process(point.z); // Will accessing z cause problems?
    }
}

In reality the code process represents is a lot more complicated and z is dependent on x and y so I am looking for a way to avoid code duplication. I will probably figure out a way to overload the function instead, but I am curious so I can learn more about generics.


Solution

  • I to know if it is possible to have an if statement in a method that will check the type of the generic used.

    Not in general, no - because of type erasure. Basically the type of T isn't known at execution time.

    You could use:

    if (point instanceof Point3D)
    

    but that's not quite the same as checking whether T itself is Point3D. It's probably a better idea though:

    public void processPoints(Point point) {
        process(point.x);
        process(point.y);
        if (point instanceof Point3D) {
            Point3D point3d = (Point3D) point;
            process(point3d.z);
        }
    }