2014年2月8日星期六

Class generic problem

For example: I have a class Abc
There is a Map, Map > mapping = new HashMap > ; ( ) ;

Class c = Class.forName (className) ;

if className The class is inherited Abc , it will execute the code below
mapping.put ("xxx", c); / / here is the problem

do not know if people understand what I mean, of course , if not generic , then it is not so much "dust " of the
------ Solution ---------- ----------------------------------

Since generics compile inspection , if without the usual cast with such wording is not compile the . We can use java generics only done at compile time checking features as long as we let the compiler can not check on the line, this time without a strong turn uses reflection to call put the best.

package test;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class Test {

public static void main(String[] args) throws ClassNotFoundException {

Map<String, Class<Test>> mapping = new HashMap<String, Class<Test>>();

String className = "xxx.xxx.xxx"; // 这里具体是什么并不重要

Class<?> c = Class.forName(className);

Method method=Map.class.getMethod("put",Object.class,Object.class);
                method.invoke(mapping,"a",c);
                System.out.println(mapping);
}
}

------ For reference only ----------------------------------- ----
One might argue that such a solution
map.put ("xxx", (Class) c );

But the problem is "(Class ) c", forced conversion, it's not back to the way the non-generic ?
------ For reference only -------------------------------------- -
did not understand what mean.
------ For reference only -------------------------------------- -?
> represents a generic , generic to Abc this subclass or for itself (Abc) type.
------ For reference only -------------------------------------- -
public class TestG {

Map map = new HashMap ();

so can not it
------ For reference only ----------------------------- ----------

package test;

import java.util.HashMap;
import java.util.Map;

public class Test {

public static void main(String[] args) throws ClassNotFoundException {

Map<String, Class<Test>> mapping = new HashMap<String, Class<Test>>();

String className = "xxx.xxx.xxx"; // 这里具体是什么并不重要

Class<?> c = Class.forName(className);

mapping.put("a", c);
}
}

Finally mapping.put compile errors , how to adjust, do not use cast
------ For reference only ---------------- -----------------------
here to do a display conversion
if (c instance of Class ) {
Class abcC = (Class ) c ;
mapping.put ("xxx", abcC);
}

没有评论:

发表评论