Search code examples
jpagenericsentity

How to make a method accepting only Entity


I would like to make a method that accept any type of javax.persistence.Entity object.

I tried this.

The Generic Method

import javax.persistence.Entity;

public <T extend Entity> void GenericMethod(T entity) {...}

The Entity Used For Test

@Entity
public class EntityObject {...}

The Test

GenericMethod(new EntityObject());

I am having an error at compilation, The method GenericMethod(T) in the type ... is not applicable for the arguments (EntityObject).

How do you limit the method to only accept object with the @Entity annotaion ???


Solution

  • Short answer is that you can't do this. At least not as a compile time check. T extend Entity would only work if Entity would be an interface or a class; in your case it's an annotation and this is forbidden by the JLS.

    The only way to do it would be via a runtime check, something like this:

    private static void test(EntityObject entityObject) {
        Annotation [] all = entityObject.getClass().getAnnotations();
        // filter on the ones you care
    }
    

    But this would only work at runtime, of course.