java - How do I use generics to call a method with a Class parameter? -


i have class uses reflection manipulate other classes:

package com.cw.cmt;  public class container<t extends class<?>> {     private final class<t> clazz;      public container(final class<t> clazz) {         this.clazz = clazz;         system.out.println("expensive constructor " + this);     }      @override     public string tostring() {         return string.format("container [clazz=%s]", clazz);     } } 

because these potentially expensive construct, want cache them in map constructed needed:

package com.cw.cmt;  import java.util.concurrent.concurrenthashmap; import java.util.concurrent.concurrentmap;  public class containercache {     private static final concurrentmap<class<?>, container<? extends class<?>>> cache = new concurrenthashmap<>();      public static <c extends class<?>> container<c> getcontainer(final class<c> clazz) {         final container<? extends class<?>> result = cache.computeifabsent(clazz, k -> new container<c>(clazz));         // nice eliminate cast!         return (container<c>) result;     } } 

i'm having trouble working out correct generic syntax invoking getcontainer method.

// parameterized method <class<string>>getcontainer(class<class<string>>) of type containercache  // not applicable arguments (class<string>) containercache.getcontainer(string.class);  // bound mismatch: generic method getcontainer(class<c>) of type containercache not applicable  // arguments (class<string>). inferred type string not valid substitute bounded  // parameter <c extends class<?>> containercache.<string>getcontainer(string.class);  // parameterized method <class<string>>getcontainer(class<class<string>>) of type containercache  // not applicable arguments (class<string>) containercache.<class<string>>getcontainer(string.class); 

i don't think can eliminate cast because map contains several "types" of containers need cast correct one. pointed out container should container<t> , few more casts in getcontainer should wanted:

public static class containercache {   private static final map<class<?>, container<?>> cache = new concurrenthashmap<>();    public static <t> container<t> getcontainer(final class<t> clazz) {     return (container<t>) cache.computeifabsent(clazz, c -> new container<> ((class<t>) c));   } }  public static class container<t> {   private final class<t> clazz;    public container(final class<t> clazz) {     this.clazz = clazz;     system.out.println("expensive constructor " + this);   }    @override   public string tostring() {     return string.format("container [clazz=%s]", clazz);   } } 

it's bit ugly don't think can better...


Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -