1 package org.codehaus.plexus.component.factory.java;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 import java.lang.reflect.Modifier;
20
21 import org.codehaus.plexus.PlexusContainer;
22 import org.codehaus.plexus.classworlds.realm.ClassRealm;
23 import org.codehaus.plexus.component.factory.AbstractComponentFactory;
24 import org.codehaus.plexus.component.factory.ComponentInstantiationException;
25 import org.codehaus.plexus.component.repository.ComponentDescriptor;
26
27
28
29
30
31
32
33 public class JavaComponentFactory extends AbstractComponentFactory {
34 public String getId() {
35 return "java";
36 }
37
38 public Object newInstance(ComponentDescriptor componentDescriptor, ClassRealm classRealm, PlexusContainer container)
39 throws ComponentInstantiationException {
40 Class implementationClass = null;
41
42 try {
43 String implementation = componentDescriptor.getImplementation();
44
45 implementationClass = classRealm.loadClass(implementation);
46
47 int modifiers = implementationClass.getModifiers();
48
49 if (Modifier.isInterface(modifiers)) {
50 throw new ComponentInstantiationException(
51 "Cannot instantiate implementation '" + implementation + "' because the class is a interface.");
52 }
53
54 if (Modifier.isAbstract(modifiers)) {
55 throw new ComponentInstantiationException(
56 "Cannot instantiate implementation '" + implementation + "' because the class is abstract.");
57 }
58
59 Object instance = implementationClass.newInstance();
60
61 return instance;
62 } catch (InstantiationException e) {
63
64
65 throw makeException(classRealm, componentDescriptor, implementationClass, e);
66 } catch (ClassNotFoundException e) {
67 throw makeException(classRealm, componentDescriptor, implementationClass, e);
68 } catch (IllegalAccessException e) {
69 throw makeException(classRealm, componentDescriptor, implementationClass, e);
70 } catch (LinkageError e) {
71 throw makeException(classRealm, componentDescriptor, implementationClass, e);
72 }
73 }
74
75 private ComponentInstantiationException makeException(
76 ClassRealm componentClassRealm,
77 ComponentDescriptor componentDescriptor,
78 Class implementationClass,
79 Throwable e) {
80
81
82
83
84
85 String msg;
86
87 if (componentClassRealm == null) {
88 msg = "classRealm is null for " + componentDescriptor;
89 } else {
90 msg = "Could not instantiate component: " + componentDescriptor.getHumanReadableKey() + " realm: "
91 + componentClassRealm.getId();
92 }
93
94 return new ComponentInstantiationException(msg, e);
95 }
96 }