MentaContainer

Compare Revisions

Ignore whitespace Rev 28 → Rev 32

/trunk/src/test/java/org/mentacontainer/impl/GenericComponentTest.java
New file
0,0 → 1,41
package org.mentacontainer.impl;
 
import junit.framework.Assert;
 
import org.junit.Test;
import org.mentacontainer.Component;
import org.mentacontainer.Container;
 
public class GenericComponentTest {
public static class SomeFactory {
public String giveMeSomething() {
return String.valueOf(System.nanoTime());
}
}
@Test
public void testGenericComponent() throws Exception {
SomeFactory factory = new SomeFactory();
Container c = new MentaContainer();
Component generic = new GenericComponent("myFactory", factory, "giveMeSomething");
c.ioc(generic);
String s1 = (String) c.get("myFactory");
Thread.sleep(5);
String s2 = (String) c.get("myFactory");
Assert.assertNotNull(s1);
Assert.assertNotNull(s2);
Assert.assertTrue(s1 != s2);
Assert.assertTrue(!s1.equals(s2));
}
}
/trunk/src/main/java/org/mentacontainer/impl/GenericComponent.java
New file
0,0 → 1,65
package org.mentacontainer.impl;
 
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 
import org.mentacontainer.Component;
import org.mentacontainer.util.FindMethod;
 
public class GenericComponent implements Component {
private final Object factory;
private final String name;
private final Method method;
public GenericComponent(String name, Object factory, String methodName) {
this.name = name;
this.factory = factory;
try {
this.method = FindMethod.getMethod(factory.getClass(), methodName, new Class[] { });
this.method.setAccessible(true);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
public Object getInstance() throws InstantiationException {
try {
return method.invoke(factory, (Object[]) null);
} catch(InvocationTargetException e) {
throw new InstantiationException("InvocationTargetException: " + method.getName() + " / " + e.getMessage());
} catch(IllegalAccessException e) {
throw new InstantiationException("IllegalAccessException: " + method.getName() + " / " + e.getMessage());
}
}
public String getName() { return name; }
public Component addInitValue(Object value) {
throw new UnsupportedOperationException();
}
public Component addProperty(String name, Object value) {
throw new UnsupportedOperationException();
}
public boolean isSingleton() { return false; }
}