2

I have a class. It will be simple container, which may contain some type T and type Optional<T> (guava Optional link) With Container.of(T) there is no problems. But, how can create Container.ofOptional(T)?
Here is my class:

public final class Container<T>{
  Class<?> firstClass;
  Class<T> seconClass;

  Container(Class<?> first, Class<T> second){
    this.firstClass = first;
    this.seconClass = second;
  }

  public static <T> Container<T> of(Class<?> first, Class<T> second){
    return new Container(first, second);
  }

  public static <T> Container<Optional<T>> ofOptional(Class<?> first, Class<T> second){
    return of(first, <what should I pass here>);
  }
}

I tried Optional.of(second) but it doesn't work.

So, in result, I want method Container.ofOptional(T) return Container<Optional<T>>

3
  • Optional.of(second) isn't viable since you claim to be returning a Container<Optional<T>>, and at best with that, you're returning an Optional<Class<T>>. I've been looking at this for a while now and I'm quite perplexed about its use case. Why are you just passing classes around instead of anything more concrete? Commented Dec 31, 2015 at 23:33
  • If you put return new Container(first, second); to ofOptional, Java compiles correctly. But, what is your purpose? What you need to do with ofOptional? Commented Dec 31, 2015 at 23:41
  • @Valijon, may be java compiles it correctly, but Intellij show me error about second argument Required Optional<T>, Found Optional Commented Jan 1, 2016 at 9:10

1 Answer 1

3

Due to type erasure, this doesn't really make sense. There's only one Optional.classOptional.of("foo").getClass() and Optional.of(3).getClass() both return the same instance — so although you can obtain an expression of type Class<Optional<T>> by lots of casting, its runtime-type will necessarily be Class<Optional> (or just null), so you can't do anything really useful with it.

So the simple answer to your question is that you can write

  public static <T> Container<Optional<T>> ofOptional(Class<?> first, Class<T> second){
    return of(first, (Class<Optional<T>>) (Class) Optional.class);
  }

but the real answer is that you shouldn't do this.

(You might want to post a new question about your real problem — the problem that Container is trying to solve — and perhaps someone can help you find a better approach.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you very much. I don't reed to post new question, because your answer solved my problem.

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.