Parameterized class, how to refer to the parameterized type of something that passed as a parameterized type

Sorry if the name sucks, don’t know how to ask this question ...

Let's say I have a Foo interface that accepts a parameter

  public interface IFoo<Bar extends IBar>{

      public Bar generateBar();
  }

and I have another class that takes a foo object and generates a bar object. I can define it like that.

 public class FooBar<Bar extends IBar, Foo extends IFoo<Bar>>{

      private Foo foo;

      public FooBar(Foo foo){
          this.foo = foo;
      }

      public Bar getBar(){
           this.foo.generateBar();
      }

All of this works great. However, it seems silly to me to define Bar as a parameter of my FooBar class. The IFoo object will be parameterized to accept the value Bar, so I would suggest that I could infer the type Bar from any parameter that has the Foo object; thus avoiding that anyone should provide two parameters every time they define a FooBar object.

, ? , Bar FooBar, Foo?

edit: , , , . , , , - , , . , , Java , , , , Bar, IFoo. IFoo, ?

+4
4

IFoo, , , - Bar, IFoo Foo.

, , IFoo, Bar IFoo .

class FooBar<Foo extends IFoo<? extends IBar>>{

getBar IBar.

public IBar getBar(){
    return this.foo.generateBar();
}
+2

, Bar, Class<Bar>. :

class FooBar ...{
    Class<Bar> barClass = ...;

    public Bar getBar(){
         return barClass.newInstance();
    }
}

barClass. , , Foo, Bar ..

:

class FooBar<T> ...{
        Class<T> someClass = ...;

        public T getInstance(){
             return someClass.newInstance();
        }
    }

Class<Bar> .

+1

, getBar . - . , .

0

, , , , , . , , , , .

FooBar :

public class FooBar<Bar extends IBar>{

  private IFoo<Bar> foo;

  public FooBar(IFoo<Bar> foo){
      this.foo = foo;
  }

  public Bar getBar(){
       this.foo.generateBar();
  }
0

Source: https://habr.com/ru/post/1612622/


All Articles