简体   繁体   中英

Use Java generics to accept and Interface and return a Class that implements that Interface

I'm writing a Class to centralise my EJB lookups. As such, I pass in an Interface to a method and use that as the basis for the EJB lookup and then return an instance of the appropriate Class.

I want to use Generics so that I don't have to cast the result when calling the method.

I have written the below, which works, but I have a bad feeling about it and I'm pretty sure it's not actually doing what I want.

public class EJBProvider {

    public static <T> T lookupEjb(Class theClass) {
        try {
            InitialContext ic = new InitialContext();

            String simpleName = String.format("java:comp/env/ejb/%s", theClass.getSimpleName());
            final T ejb = (T)ic.lookup(simpleName);
            return ejb;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}


private MyEjbLocal myEjb = EJBProvider.lookupEjb(MyEjbLocal.class);

As SLaks suggests, Class<? extends T> Class<? extends T> enforces the type correctly.

I also integrated Gábor Bakos suggestions of using theClass.cast();

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