Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java. Howto change methods signature

Is it possible to change a methods signature in Java depending on the parameter?

Example:

Given a class, with a generic parameter MyItem<T>. Assume this class has a method, which returns T Given a second class 'myReturner()' which contains method myreturn(MyItem<T>).

Question:

Can i make myreturn(MyItem<T>) return a T object, depending on the generic parameter of MyItem?

I suppose it is not possible, because the signature is set during compile time in Java, and T is not known at compile time. If so, what is the best way to simulate a method, which will return different objects, depending on parameter? Is writing an own method for each parameter type the only way?

like image 389
Skip Avatar asked Jan 27 '26 01:01

Skip


2 Answers

Something like this?

private <T> T getService(Class<T> type) {
    T service = ServiceTracker.retrieveService(type);
    return service;
}
like image 134
rodrigoap Avatar answered Jan 28 '26 16:01

rodrigoap


Do you mean something like this:

<T> T myMethod(MyItem<T> item) 

?

like image 37
Puce Avatar answered Jan 28 '26 15:01

Puce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!