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,405
  • 35
  • 46
Skip
  • 6,240
  • 11
  • 67
  • 117
  • 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,405
  • 35
  • 46
3

Do you mean something like this:

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

?

Puce
  • 37,247
  • 13
  • 80
  • 152
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,405
  • 8
  • 54
  • 87
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,339
  • 5
  • 30
  • 63
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
  • 14,219
  • 5
  • 40
  • 60