3

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?

rodrigoap
  • 7,302
  • 34
  • 46
Skip
  • 5,771
  • 10
  • 61
  • 111
  • As to why it is possible: when compiling Java simply outputs `Object myreturn(MyItem)` as a method, removing any generic information. This method obviously can accept any object. – Viruzzo Dec 02 '11 at 14:36
  • As far as I can guess Viruzzo's link should be somewhere at this link instead: docs.oracle.com/javase/tutorial/java/generics/methods.html – Crowie May 04 '14 at 15:34

5 Answers5

7

Something like this?

private <T> T getService(Class<T> type) {
    T service = ServiceTracker.retrieveService(type);
    return service;
}
rodrigoap
  • 7,302
  • 34
  • 46
3

Do you mean something like this:

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

?

Puce
  • 36,099
  • 12
  • 75
  • 145
0

You can, if you also make the whole class generic to that same type T, something like:

import java.util.ArrayList;

public class MyReturn<T> {

    public T myReturn(ArrayList<T> list){
        return null; //Your code here
    }
}
Miquel
  • 15,055
  • 8
  • 52
  • 86
0

A generic return type is perfectly well possible. Look for instance here: How do I make the method return type generic? or here: Java Generics: Generic type defined as return type only

Community
  • 1
  • 1
Pieter
  • 3,299
  • 4
  • 29
  • 61
0

I think you want something like this:

public static void main(String[] args) {
    String bla = myMethod(new MyItem<String>());
}

public static <T> T myMethod(MyItem<T> item) {
    return null;
}

public class MyItem<T> {
    //just a dummy
}
Fabian Barney
  • 13,533
  • 4
  • 39
  • 60