자바 리플렉션을 사용하여 놀고 있었고 다른 클래스에서 선언 된 메서드에서 메커니즘 캐싱 메서드를 만들고 싶습니다. 임의의 동작을 방지하기 위해 캐시에 동일한 서명이있는 메서드를로드하는 것을 금지하고 싶습니다 (다른 클래스에 선언 된 메서드는 동일한 서명을 가질 수 있습니다).Set의 contains() 메서드를 재정의해도 되나요?
이 작업을 수행하는 유일한 방법은 메서드를 캐시하는 집합의 contains() 메서드를 재정의하는 것입니다.
위험 할 수 있습니까? 이것을 달성하기 위해 더 좋은 생각이 있습니까?
private final Set<Method> methodsCache;
public MyMethodCachingClass(Set<Class<?>> classes) {
methodsCache = new HashSet<Method>(){
private static final long serialVersionUID = -1467698582662452923L;
/**
* Overwriting the contains method of this Set so that we don't allow multiple methods with the same signature,
* even if they are declared in different classes.
*/
@Override
public boolean contains(Object o) {
if (!(o instanceof Method)) {
return false;
}
Method method = (Method) o;
for (Method m : this) {
if (method.getName().equals(m.getName()) && method.getParameterTypes().equals(m.getParameterTypes())) {
return true;
}
}
return false;
}
};
for (Class<?> c : classes) {
for (Method m : c.getDeclaredMethods()) {
if (methodsCache.contains(m)) {
throw new IllegalArgumentException("The method " + m.getName() + " exists with the same signature in two different classes.");
}
methodsCache.add(m);
}
}
}
고마워요!
실제로 선언 된 클래스에 관계없이 한 버전의 메소드 만 캐시하고 싶습니까? 그것은 이상한 요구 사항처럼 보입니다 ... – ig0774
@ ig0774 : 나는 어떤 요구 조건도 가지고 있지 않습니다. 나는 단지 놀고 있습니다. 그러나 나에게 이상하지 않은 것처럼 보입니다. 웹 서버에서 메소드를 실행해야하는 웹 서블릿이 있다면 어떨까요? 코드 가독성을 높이기 위해 다른 클래스의 실행 가능 메소드를 선언 할 수 있기를 원할 것입니다. 클라이언트가 메소드를 선언 한 위치에 대해 걱정할 필요가 없다고 확신 할 수 있습니다. – nbarraille