Trying
Trying

Reputation: 14278

Generic type as a annotation

I am writing a generic class where i am exposing a no of db related operation like find, findById, save etc. So have a function like:

public <T> T getById(Class<T> type, long id){
        return <some entityManager>.find(type, id);
    }

But if you see carefully T type classes would always be annotated with @Entity so how could i put that into my code. for example some thing like:

Class<? extends Entity> (i know this is incorrect but wanted to put my point clearly what i want) Thanks.

Upvotes: 1

Views: 66

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279990

If I understand correctly and you only want to be able to pass Class objects for classes annotated with a certain annotation, then the answer is it's impossible. You can't put such a restriction at compile time.

At runtime, you'd have to do the check yourself with reflection, Class#getAnnotation(Class).

Upvotes: 1

Related Questions