Question

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.

Was it helpful?

Solution 2

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);
    }
}

OTHER TIPS

How about plain old overloading and avoid generics?

public void processPoints(final Point2D point)
{
    process(point.x);
    process(point.y);
}

public void processPoints(final Point3D point)
{
    process(point.x);
    process(point.y);
    process(point.z);
}

If you only have instances of Point2D and Point3D why would you use a generic parameter T?

You should look for other ways to remove code duplication instead of using instanceof or the like.

No it is not possible, because of type erasure in runtime. JVM knows (almost) nothing about generics, they are mainly meant for compiler to check types. After checking types using generics compiler replaces all generic types, say List<String> becomes List<Object> after compilation, so it's not detectable at runtime.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top