简体   繁体   中英

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?

Something like this?

private <T> T getService(Class<T> type) {
    T service = ServiceTracker.retrieveService(type);
    return service;
}

Do you mean something like this:

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

?

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
    }
}

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM