简体   繁体   中英

instance of generic type in Java

I want to write a little "factory" for a number of methods that has the same set of arguments. Here is my code so far (it is so wrong that event the IDE won't let it it pass)

 public <T> T callServer(String param1, String param2, String param3){
    if (T instanceof Type1 ){
        return (T) callFunctionServerType1(param1,  param2, param3);
    }
    else if (T instanceof Type2)
        return  (T) callFunctionServerType2(param1,  param2, param3);
    return null;
}

The IDE says that and expression is expected and underlines each T thas is just after the if statement (if (T ...) ). Can you help me to solve this problem.

You can pass needed class of T as additional parameter

public <T> T callServer(String param1, String param2, String param3, Class<? extends T> returnClass)
{
  if (Type1.class.isAssignableFrom(returnClass)) {
     ...

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