1 | /* |
2 | * JTiger Unit Testing Framework for J2SE 1.5 |
3 | * Copyright (C) 2005 Tony Morris |
4 | * |
5 | * This software is licenced under the |
6 | * Common Public Licence version 1.0 |
7 | * http://www.opensource.org/licenses/cpl1.0.php |
8 | * |
9 | * You received a copy of this licence with this software. |
10 | */ |
11 | package org.jtiger.framework; |
12 | |
13 | import java.lang.reflect.Constructor; |
14 | import java.lang.reflect.InvocationTargetException; |
15 | |
16 | final class ClassConstructionFactory |
17 | { |
18 | private ClassConstructionFactory() |
19 | { |
20 | |
21 | } |
22 | |
23 | static <T> ClassConstruction newClassConstruction() |
24 | { |
25 | return new ClassConstructionImpl<T>(); |
26 | } |
27 | |
28 | private static final class ClassConstructionImpl<T> implements ClassConstruction |
29 | { |
30 | ClassConstructionImpl() |
31 | { |
32 | |
33 | } |
34 | |
35 | public <T> T construct(final Class<? extends T> c) |
36 | throws InstantiationException, IllegalAccessException, InvocationTargetException |
37 | { |
38 | if(c == null) |
39 | { |
40 | return null; |
41 | } |
42 | |
43 | try |
44 | { |
45 | final Constructor<? extends T> strCtor = c.getDeclaredConstructor(String.class); |
46 | |
47 | if(!strCtor.isAccessible()) |
48 | { |
49 | strCtor.setAccessible(true); |
50 | } |
51 | |
52 | return strCtor.newInstance(c.getCanonicalName()); |
53 | } |
54 | catch(NoSuchMethodException e1) |
55 | { |
56 | try |
57 | { |
58 | final Constructor<? extends T> noArgsCtor = c.getDeclaredConstructor(); |
59 | |
60 | if(!noArgsCtor.isAccessible()) |
61 | { |
62 | noArgsCtor.setAccessible(true); |
63 | } |
64 | |
65 | return noArgsCtor.newInstance(); |
66 | } |
67 | catch(NoSuchMethodException e2) |
68 | { |
69 | return null; |
70 | } |
71 | } |
72 | } |
73 | } |
74 | } |