0

I have an AbstractCacheBlock and I want to define a class CacheSet that contains many classes extending AbstractCacheBlock. I believe what I want is something like

public class CacheSet<? extend AbstractCacheBlock>

But this doesnt appear valid. How can I refer to that class then? Usually it looks something like

public class CacheSet<T> {
    public void something() {
        T t = new T();
    }

What do I use in place of the T then?

2
  • 2
    Why do you want to create instances in a CacheSet? Shouldn't you be adding already created instances? Commented Nov 5, 2013 at 13:38
  • @SotiriosDelimanolis, maybe you are right I should initialize it outside Commented Nov 5, 2013 at 13:42

2 Answers 2

9

The only way to intialize an instance of a generic type is by passing an instance of the Class, something like:

public class CacheSet<T>
{
    private Class<T> clazz;

    public CacheSet(Class<T> clazz)
    {
        this.clazz = clazz;
    }

    public void something()
    {
        T t = clazz.newInstance();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

+ probably something like: public class CacheSet<T extends AbstractCacheBlock>{...}
1

Creating object with T is not doable. You can add dependency to class that can create a new T object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.