1

I have an abstract class as follows:

@Component
public abstract class B<T extends C, S extends D>{
    @Autowired
    private JpaRepository repository;
    public void add(){
        repository.add(); //this add method takes an argument of a class object of T 
    }
    public void delete(){
        repository.delete();//this add method takes an argument of a class object of S
    }
}

I realize I have two options to fix this. Do something similar to this where I do ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments() or I do something similar to below (not exact but you get the idea) in the sub class:

@Component
public abstract class B<T extends C, S extends D>{
    @Autowired
    private JpaRepository repository;
    private Class<T> classT;
    private Class<S> classS;
    public B(Class<T> classT, Class<S> classS){
        this.classT = classT;
        this.classS = classS;
    }
    public void add(){
        repository.add(); //this add method takes an argument of a class object of T 
    }
    public void delete(){
        repository.delete();//this add method takes an argument of a class object of S
    }
}
public class A extends B<X, Y>{
    public A(){
        super(X.class, Y.class);
    }
}

I wonder if there is a better way to achieve this. Specifically if I want to ensure type safety without having to subclass developer write too much code. The second approach would have been fine but every subclass having to deal with this seems a little annoying, not just to mention Spring Java @Autowired annotation has chances of getting confused with multiple constructors.

Community
  • 1
  • 1
as3rdaccount
  • 3,711
  • 12
  • 42
  • 62
  • Eh? Could you post the *real* intended code please? Surely your own `add()` methods will take an argument of type T? which is passed directly to `repository.add(...)`? – user207421 May 10 '16 at 04:31

1 Answers1

-1

Have you tried Simply:

{Object}.get class()?

cd3
  • 117
  • 1
  • 9