Blame |
Last modification |
View Log
| RSS feed
package org.mentacontainer.impl;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import org.mentacontainer.util.InjectionUtils;
public class Dependency
{
private final String target
;
private String source
;
private final Class<? extends Object> klass
;
private Map<String,
Method> cache =
new HashMap<String,
Method>();
private Map<Object,
Object> received =
new WeakHashMap<Object,
Object>();
public Dependency
(String target,
Class<? extends Object> klass,
String source
) {
this.
klass = klass
;
this.
target = target
;
this.
source = source
;
}
public Dependency
(String target,
Class<? extends Object> klass
) {
this(target, klass, target
);
}
public String getTarget
() {
return target
;
}
public String getSource
() {
return source
;
}
public Class<? extends Object> getDependencyClass
() {
return klass
;
}
public int hashCode
() {
return klass.
hashCode() * 62 + target.
hashCode() * 31 + source.
hashCode();
}
public boolean equals
(Object obj
) {
if (!(obj
instanceof Dependency
)) return false;
Dependency d =
(Dependency
) obj
;
if (!d.
klass.
equals(this.
klass)) return false;
return true;
}
public Method getMethod
(Class<? extends Object> targetClass
) {
String className = targetClass.
getName();
// first check cache...
Method m =
null;
synchronized(cache
) {
m = cache.
get(className
);
}
if (m ==
null && cache.
containsKey(className
)) return null; // it is null...
if (m
!=
null) return m
;
m = InjectionUtils.
findMethodToInject(targetClass, target, klass
);
if (m
!=
null) {
synchronized(cache
) {
cache.
put(className, m
);
}
return m
;
}
synchronized(cache
) {
// save null to indicate there is no method here... (so you don't do again to find null !!!
cache.
put(className,
null);
}
return null;
}
/*
* Check if this object has already received the dependency, because we don't want to
* inject every time. Injecting just once is the correct behavior.
*/
public boolean hasAlreadyReceived
(Object target
) {
synchronized(received
) {
return received.
containsKey(target
);
}
}
/*
* Flag that this object has already received the dependency.
*/
public void setAlreadyReceived
(Object target
) {
synchronized(received
) {
received.
put(target,
null);
}
}
}