2014-07-14 2 views
1

좋아, 모든 내 인근에 기본 클래스가 있으므로 BaseEntity으로 호출 할 수 있습니다. 당신이 볼 수 있듯이개체 유형에 따라 호출 할 메서드를 결정하십시오.

A extends BaseEntity { ... } 

B extends BaseEntitay { 
    private A myA; 
} 

는, 하나의 엔티티가 다른 엔티티 관계를 가질 수 있습니다 예를 들어, 그래서 다른 모든 엔티티 클래스는,이 일을 형성 상속합니다. D는 C는 B가 ...

문제를 가지고있다가 같은 는 사실,하는 hierachy가있다 : 나는 diffrent 기본 클래스 타입의 객체에 메소드를 호출하는 클래스를 생성 할 . 아이디어는이 같은 공공 방법 것이 었습니다 :

public BaseClass getLowerLayer(BaseClass entity) { 
    return getLowerLayer(entity); 
} 

그리고 같은 클래스에 필요한 모든 방법 :

public B getLowerLayer(C entit) { 
    return someFancyMethod(entity); // this is defined elsewhere to get the right entity. I can not modify it. 
} 

을하지만 무한 루프를 생성으로이 작동하지 않습니다. 최소한 침윤성 방식으로이 (without instanceof)을 만드는 방법이 있습니까?

+1

냄새가 나는 디자인 문제가 있습니다. 당신이하려는 일을 우리에게 말해 줄 수 있습니까? –

+1

'다른 기본 클래스 유형의 객체에 대해 메소드를 호출 할 클래스를 만들고 싶습니다. '할 수 없습니다. 다른 객체의 메소드를 사용할 수 있지만 계층 구조의 메소드는 사용할 수 없습니다. Java에 의해 호출됩니다. – Smutje

답변

2

나는 당신이 무슨 뜻인지 알고 있다고 생각합니다. 이것은 다형성의 완벽한 예가 잘못된 것이 아닙니다.

기본 클래스를 하위 클래스로 확장한다는 사실은 수퍼 클래스가이 하위 클래스가 자신을 확장한다는 것을 어떻게 알 수 있는지 궁금하게 만듭니다. 나는 그것을위한 하나의 겸손한 해결책이있다. 나는 설명 철저한 좋은 아니라고하지만 예를 들어 줄 것이다 : 당신은 슈퍼 클래스 그가 무엇 서브 클래스 알려 일반적인 태그를 내 서브 클래스 내 추상 클래스를 확장 한보고 사용 수있는 지금

public abstract class AbstractDAO<T extends Serializable> { 

    protected EntityManager em; 
    protected Class<?> entityClass; 

    public AbstractDAO(EntityManager em, Class<?> c) { 
     this.em = em; 
     this.entityClass = c; 
    } 

    @SuppressWarnings("unchecked") 
    public T findById(Serializable id) { 
     if (id == null) { 
      throw new PersistenceException("id cannot be null"); 
     } 
     return (T) em.find(entityClass, id); 
    } 

} 

public class CustomerDAO extends AbstractDAO<Customer> { 

    public CustomerDAO(EntityManager em) { 
     super(em, Customer.class); 
    } 
} 

public class OrderDAO extends AbstractDAO<Order> { 

    public OrderDAO(EntityManager em) { 
     super(em, Order.class); 
    } 
} 

EntityManager em = PersistenceManager.getEntityManager(); 
CustomerDAO customDAO = new CustomerDAO(em); 
customDAO.findById(45325L); 

내가 만든 맞춤 클래스로 "PersistenceManager".

관련 문제