How get Instance using Generic approach

Still Learning :

I am trying to build one page assembler using generic approach. Following is piece of code. In this code IEntity is marker interface for DB entities.

public abstract class PageHrefBuilder implements HrefBuilder<IEntity, PageLinks> {

    @Override
    public PageLinks buildLinks(IEntity entity) {
        return null;
    }
}

public interface HrefBuilder<E extends IEntity, L extends Links> {

    public L buildLinks(E dto);
}

So we have one interface says can build links using IEntity type of class and return Links type of value. So I want to write some common code in abstract class and abstract class does not know what type entity it suppose to deal with. For example entity can UserEntity, OrderEntity and so on.

So my question is how in abstract class I can get the class instance to build links with using instanceof or if else approach.

Could someone help me on this.

Shalan93 :

You can make your buildLinks method to take Class<T> parameter instead of the object you have to pass.

so it will be

public L buildLinks(Class<E> dto);

then in your abstract class

@Override
public PageLinks buildLinks(Class<IEntity> dto) {
    return dto.newInstance();
}

Hope this answer could help you.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=356406&siteId=1