简体   繁体   中英

yet another confusing generics in Java

I've got a static method inside Utility class :

public static final <T extends Foo & IBar>  Foo1<T> getBaz(Class<T> fooAndIBarClazz)

I have another class:

public class FooBar<T extends Foo> {
     private Class<T> fooClazz;
//...
}

From inside the instance of FooBar I want to call Utility.getBaz()

public void aMethod() {
   Utility.getBaz(fooClazz); // fails with not a valid substitute for the bounded parameter
   //Utility.<IBar>getBaz(fooClazz); // fails as well
}

Is it possible to call the utility method in this generic way without additional casting?

Generics in Java add compile-time type checking, and basically help you to avoid casting. If there's something you cannot do with casting, you also won't be able to do it with generics.

If you cannot confirm that the class you're calling the method with implements IBar, what do you expect the called method to do with it? Clearly, it requires the methods that IBar defines (otherwise it wouldn't have that signature). So it cannot perform its job.

Your posted code seemed incomplete. This all works for me.

Foobar

public class FooBar<T extends Foo> {

    public void aMethod() { 
        Utility.getBaz( Foo.class ) ;
    }

}

Foo

public class Foo<T> implements IBar {

}

Utility

public class Utility {
    public static final <T extends Foo & IBar>  Foo<T> getBaz(Class<T> fooAndIBarClazz){

        try {
            return fooAndIBarClazz.newInstance() ;
        } catch( InstantiationException e ) { 
            e.printStackTrace();
        } catch( IllegalAccessException e ) {
            e.printStackTrace();
        } 

        return null ;  

    }
}

Ibar

public interface IBar {

}

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