TestAutomator
TestAutomator

Reputation: 299

How to resolve: parameter never used with T type while T itself is used?

I am facing with a Java Warning ("Parameter myParameter is never used") on my generic method where I use type of the parameter (T) but not the parameter value itself. Can I avoid this warning without using SuppressWarnings annotation?

private <T extends MyInterface> MyGenericObject<T> init(Class<T> myParameter) {
   // lots of common code here ... and:
   return new MyGenericObject<T>();
}

The way I use this method at the moment:

MyGenericObject<MyClassA> aInstance = init(MyClassA.class);
MyGenericObject<MyClassB> bInstance = init(MyClassB.class);

Perhaps there must be a way to pass only the type to my method without parameter, but I cannot find the way for it. Could you please help me out with that?

Upvotes: 0

Views: 720

Answers (1)

Andy Turner
Andy Turner

Reputation: 140319

where I use type of the parameter (T)

But you don't need myParameter to provide you with T. It will work generically without it:

private <T extends MyInterface> MyGenericObject<T> init() {
   // lots of common code here ... and:
   return new MyGenericObject<T>();
}

// and invoke like:
MyGenericObject<MyClassA> aInstance = init();
MyGenericObject<MyClassB> bInstance = init();

A type parameter isn't really a "thing" you use. It's just an instruction to the compiler to make sure that all of the types which refer to T are compatible.

Upvotes: 1

Related Questions