/**
 * Constructs an exception of the specified type with the given message.
 * 
 * Generic Parameters: T - the type of the exception to be created
 * 
 * Parameters: exceptionClass - the exception class message - the message
 * 
 * Returns: the constructed exception instance (not null)
 * 
 * Throws: Exception if any error occurred when using the reflection
 * 
 * Implementation Notes: 1. Constructor<T> constructor =
 * exceptionClass.getConstructor(String.class); 2. T result =
 * constructor.newInstance(message); 3. Return result.
 * 
 * Note: exceptions are populated without wrapping in this method.
 * 
 * @throws Exception
 *             if any error occurred when using the reflection
 * @param message
 *            the message
 * @param exceptionClass
 *            the exception class
 * @return the constructed exception instance (not null)
 */
static <T extends Throwable> T constructException(Class<T> exceptionClass,
String message) {
Constructor<T> constructor = exceptionClass
.getConstructor(String.class);
T result = constructor.newInstance(message);
return result;
                  //以上是我的代码,但是这代码是不能通过编译的。不知道怎么写才能满足题目要求啊
}是应该 static <T extends Throwable> T constructException(Class<T> exceptionClass,
String message) {
try{
Constructor<T> constructor = exceptionClass
.getConstructor(String.class);
T result = constructor.newInstance(message);
return result;
}
catch(Exception ex){

}
return null;
}还是这样 static <T extends Throwable> T constructException(Class<T> exceptionClass,
String message) throws Exception {
Constructor<T> constructor = exceptionClass
.getConstructor(String.class);
T result = constructor.newInstance(message);
return result; }这两种似乎都不对,但是能通过编译,求高人指点,满足题目意思的写法

解决方案 »

  1.   

    天哪大哥就是异常没捕捉啊 你要确保constructor.newInstance(message);
    返回的对象能转换成 T result 啊
      

  2.   

    Note: exceptions are populated without wrapping in this method.
    是什么意思,能解释下吗?
      

  3.   


    我觉得意思就是: 异常填穿的时候,你不能直接包装一下。  也就是说:你不能直接return (T)new Throwable(message);  
      

  4.   

    Constructor<T> constructor = exceptionClass.getConstructor(String.class);
    这里会抛出异常,因为不能保证exceptionClass指定的类对象一定有个String参数的构造函数
      

  5.   

    T result = (T)constructor.newInstance(message);
    要强值类型转换一下,方法返回的是固定的Object对象类型