-1

I would like to return generic object, but I am getting error about wrong provided return object - Provided: Human, Expected: T

Class that contains function to return generic object:

public class DataHuman<T extends HumanProcess>  {

    public T getObject() {
        return Human.builder().build();
    }
}

Interface:

public interface HumanProcess {
}

Object that extends interface:

@Data
@Builder
public class Human implements HumanProcess {

    private String name;
}

I would like to create more class like Human that implements HumanProcess and return it in getObject().

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
kamil wilk
  • 117
  • 7
  • Builder is from lombok – kamil wilk Apr 02 '21 at 10:01
  • 2
    A `Human` is no `T` - if `T` is `SomeSpecificSubclass` which `extends Human` then you cannot simply return a bare and basic `Human`. – luk2302 Apr 02 '21 at 10:01
  • you can use `HumanProcess ` as a type return of your method `getObject` – Zeuzif Apr 02 '21 at 10:08
  • @HadesZazif then what is the point of `T` in the first place if you never use it? OP simply needs to read a couple tutorials on generics and get used to them. – luk2302 Apr 02 '21 at 10:09
  • It doesn't seem like this is really meant to be generic in the first place, as @HadesZazif said it really just depends on a `HumanProcess`. – Henry Twist Apr 02 '21 at 10:09
  • Does this answer your question? [How to implement factory pattern with generics in Java?](https://stackoverflow.com/questions/34291714/how-to-implement-factory-pattern-with-generics-in-java) – luk2302 Apr 02 '21 at 10:11
  • @luk2302 the OP seems to be after Factory method, not Factory – Boris Strandjev Apr 02 '21 at 11:29

1 Answers1

0

This gets obvious of what is broken once you introduce one more implementation of HumanProcess:

static class AlmostHuman implements HumanProcess {

}

And (for the sake of the example), do:

return (T)Human.builder().build();

This cast is useless, since the compiler does not enforce it in any way, but at least the code compiles. But of course if you use it in the form of :

 DataHuman<AlmostHuman> dh = new DataHuman<>();
 AlmostHuman almost = dh.getObject();

it will fail at runtime. Which should be obvious, a Human can not be cast to AlmostHuman.

The solution in your case could be to return HumanProcess in the getObject method:

static class DataHuman<T extends HumanProcess>  {

    public HumanProcess getObject() {
        return Human.builder().build();
    }
} 
Eugene
  • 117,005
  • 15
  • 201
  • 306