2013-03-26 64 views
0

我写这将通过它尝试了class.cast验证属性的通用方法,但我不断收到一个ClassCastExceptionClassCastException异常使用Class.cast使用泛型

...类来测试

public <T> T get(Properties p, String propKey, Class<T> clazz) throws Exception { 

    T val = null; 

    Object propValue = p.get(propKey); 

    if(propValue== null) { 
     throw new Exception("Property (" + propKey + ") is null"); 
    } 

    try { 
     val = clazz.cast(propValue); // MARKER 

    } catch(Exception e) { 
     throw new Exception("Property (" + propKey + ") value is invalid value of type (" + clazz + ")", e); 
    } 



    return val; 
} 

...测试类

@Before 
public void setUp() { 
    propUtil = new PropUtil(); 
    properties = new Properties(); 
    properties.setProperty("test.int.prop", "3"); 
} 

@Test 
public void testGet() { 

    try { 

     assertEquals(new Integer(3), propUtil.get(properties, "test.int.prop", Integer.class)); 
    } catch (Exception e) { 
     System.out.println(e); 
    } 
} 

在MARKER在注释中的代码导致ClassCastException异常。

任何想法非常赞赏。

回答

0

感谢您的回复。我意识到从String到Integer投射的基本动作是不可能的。我只是想让方法变得更加轻松,并为我进行转换检查。我刚刚制定了我在使用Reflection查找的解决方案:

Object propValue = p.get(propKey); 
    Constructor<T> constructor = clazz.getConstructor(String.class); 
    val = constructor.newInstance(propValue); 

即使用接受String.class的公共构造函数(即,字符串属性值)

作品一个款待。

+1

不错的解决方法,如果没有该签名的构造函数,[NoSuchMethodException](http://docs.oracle.com/javase/6/docs/api/java/lang/NoSuchMethodException.html)被抛出女巫似乎在你的代码中处理。 – A4L 2013-03-26 20:58:42

2

假设Properties这里是java.util.Properties,值始终为String s。

您应该使用getProperty()方法,而不是get()方法恰好是从HashTable可见的,因为这个类拨回当Java乡亲约组成与继承少小心。

+0

是的。它们始终是String,但属性将包含String,Integers和Doubles,所以我希望泛型方法执行转换并在实际值不可分配类时引发异常。 – solarwind 2013-03-26 20:24:11

3

Properties类是Hashtable商店String对象,特别是当您拨打setProperty时。您已添加String“3”,而不是整数3。您正在有效尝试投射“3”作为Integer,以便正确投出ClassCastException。尝试

assertEquals("3", propUtil.get(properties, "test.int.prop", String.class)); 

或者,如果你想get返回Integer,那么就使用一个Hashtable<String, Integer>,或者甚至更好,使用HashMap<String, Integer>

+1

@Downvoter,请解释您为什么downvoted。 – rgettman 2013-03-26 20:38:54

+0

谢谢。请参阅下面的答案。 – solarwind 2013-03-26 21:13:34

1

此行

properties.setProperty("test.int.prop", "3"); 

把一个java.lang.String在性能

和你传递Integer.class你泛型方法。所以预计ClassCastException

如果你想测试Integer.class你必须把一个整数

properties.put("test.int.prop", 3); 

注意,在上述行使用put因为Properties类扩展Hashtable

如果你的意图是把一个String和测试Integer然后你必须以某种方式parse该字符串到一个整数值

+2

'setProperty'方法需要一个'String'作为值,而不是'int'。 – rgettman 2013-03-26 20:25:16

+0

@rgettman,复制粘贴过快,修复它,谢谢! – A4L 2013-03-26 20:30:39

+0

谢谢。请参阅下面的答案。 – solarwind 2013-03-26 20:48:22