How to return different types in a method using generics?Differences between HashMap and Hashtable?How to generate a random alpha-numeric string?Create Generic method constraining T to an EnumWhat is the difference between public, protected, package-private and private in Java?How do I use reflection to call a generic method?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How do I make the method return type generic?How to create a generic array in Java?How to get a class instance of generics type T

Why don't they build airplanes from 3D printer plastic?

What is this red bug infesting some trees in southern Germany?

Finder/Terminal: Find files that contain less than 21 lines of text

Is mathematics truth?

MOSFET broke after attaching capacitor bank

Would you recommend a keyboard for beginners with or without lights in keys for learning?

How did Gollum know Sauron was gathering the Haradrim to make war?

std::tuple sizeof, is it a missed optimization?

What exactly is a softlock?

Travel to USA with a stuffed puppet

Do I need to get a noble in order to win Splendor?

If p-value is exactly 1 (1.0000000), what are the confidence interval limits?

a harmful idea/plan

Did Alan Turing's student Robin Gandy assert that Charles Babbage had no notion of a universal computing machine?

Punishment in pacifist society

Time to call the bluff

What is the most likely cause of short, quick, and useless reviews?

Does POSIX guarantee the paths to any standard utilities?

Which is the best password hashing algorithm in .NET Core?

Count rook moves 1D

Go for an isolated pawn

Can I sleep overnight at Stansted Airport

Why do we need explainable AI?

Can a country avoid prosecution for crimes against humanity by denying it happened?



How to return different types in a method using generics?


Differences between HashMap and Hashtable?How to generate a random alpha-numeric string?Create Generic method constraining T to an EnumWhat is the difference between public, protected, package-private and private in Java?How do I use reflection to call a generic method?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How do I make the method return type generic?How to create a generic array in Java?How to get a class instance of generics type T






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I want to return different class types in java using generics, But there is a mistake.



These return values have their unique filed, so i don't want to use their parent class as a return type.



Here is the code:



public class Client 
public static void main(String[] args)
Client c = new Client();
A a = c.gets(1);
System.out.println(a.aFiled);
B b = c.gets(2);
System.out.println(b.bFiled);



public <T extends Root> T gets(int type)
switch (type)
case 1:
return new A();
case 2:
return new B();
default:
throw new RuntimeException();




class Root
String name;


class A extends Root
int aFiled;


class B extends Root
int bFiled;






The error occurs inside switch




"incompatible types"

Required: T

Found: Client.A




I mean to return someclass extends Root, I don't know why it is wrong.

I'd appreciate it if someone could explain it to me.










share|improve this question
































    1















    I want to return different class types in java using generics, But there is a mistake.



    These return values have their unique filed, so i don't want to use their parent class as a return type.



    Here is the code:



    public class Client 
    public static void main(String[] args)
    Client c = new Client();
    A a = c.gets(1);
    System.out.println(a.aFiled);
    B b = c.gets(2);
    System.out.println(b.bFiled);



    public <T extends Root> T gets(int type)
    switch (type)
    case 1:
    return new A();
    case 2:
    return new B();
    default:
    throw new RuntimeException();




    class Root
    String name;


    class A extends Root
    int aFiled;


    class B extends Root
    int bFiled;






    The error occurs inside switch




    "incompatible types"

    Required: T

    Found: Client.A




    I mean to return someclass extends Root, I don't know why it is wrong.

    I'd appreciate it if someone could explain it to me.










    share|improve this question




























      1












      1








      1








      I want to return different class types in java using generics, But there is a mistake.



      These return values have their unique filed, so i don't want to use their parent class as a return type.



      Here is the code:



      public class Client 
      public static void main(String[] args)
      Client c = new Client();
      A a = c.gets(1);
      System.out.println(a.aFiled);
      B b = c.gets(2);
      System.out.println(b.bFiled);



      public <T extends Root> T gets(int type)
      switch (type)
      case 1:
      return new A();
      case 2:
      return new B();
      default:
      throw new RuntimeException();




      class Root
      String name;


      class A extends Root
      int aFiled;


      class B extends Root
      int bFiled;






      The error occurs inside switch




      "incompatible types"

      Required: T

      Found: Client.A




      I mean to return someclass extends Root, I don't know why it is wrong.

      I'd appreciate it if someone could explain it to me.










      share|improve this question
















      I want to return different class types in java using generics, But there is a mistake.



      These return values have their unique filed, so i don't want to use their parent class as a return type.



      Here is the code:



      public class Client 
      public static void main(String[] args)
      Client c = new Client();
      A a = c.gets(1);
      System.out.println(a.aFiled);
      B b = c.gets(2);
      System.out.println(b.bFiled);



      public <T extends Root> T gets(int type)
      switch (type)
      case 1:
      return new A();
      case 2:
      return new B();
      default:
      throw new RuntimeException();




      class Root
      String name;


      class A extends Root
      int aFiled;


      class B extends Root
      int bFiled;






      The error occurs inside switch




      "incompatible types"

      Required: T

      Found: Client.A




      I mean to return someclass extends Root, I don't know why it is wrong.

      I'd appreciate it if someone could explain it to me.







      java generics






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 28 at 3:28







      Saber

















      asked Mar 28 at 3:22









      SaberSaber

      8510 bronze badges




      8510 bronze badges

























          3 Answers
          3






          active

          oldest

          votes


















          4
















          In generic methods, the type is inferred by the compiler using the actual arguments. But your argument doesn't have any type T. You can send another parameter Class<T> to tell the type of the return value:



          public <T extends Root> T gets(int type, Class<T> c) 
          switch (type)
          case 1:
          return c.cast(new A());
          case 2:
          return c.cast(new B());
          default:
          throw new RuntimeException();




          But in your case you don't know the type before you call this method.



          So all you can do is make this method non-generic and change return type to just Root. Then you can do instanceof check to identify the class, perform casting, and then get the relevant fields.



          It doesn't make sense to make this method generic anyway, because generic methods can work with different type of supplied data. But in your case it's always an int. So I would say your method is not really generic.






          share|improve this answer






















          • 1





            That code is error prone and will cause ClassCastException

            – Sean F
            Mar 28 at 14:33











          • @SeanF I agree. But if the OP was actually going to use it, I would do a c.equals(A.class) check.

            – Kartik
            Mar 28 at 23:14


















          0
















          The method indicates that there is a T that extends Root which is the return type. However, until the method is used somewhere, you don't know which class that is. You don't know if T will be A, or B, or something else. Each time it is used it will be exactly one subclass of Root.



          But here your code is assuming it will be both A and B at the same time. In fact, T might be neither. If T is A, you cannot return an instance of B. If T is B, you cannot return an instance of A. If T is neither A nor B, you cannot return either an instance of A or B.



          You have to return an instance of T.



          One thing you can do is not use generics and just return Root.






          share|improve this answer
































            0
















            You can modify your method as below by casting to T.



             public <T extends Root> T gets(int type) 
            switch (type)
            case 1:
            return (T) new A();
            case 2:
            return (T) new B();
            default:
            throw new RuntimeException();







            share|improve this answer

























            • That is error prone and will cause ClassCastException

              – Sean F
              Mar 28 at 14:32













            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55389681%2fhow-to-return-different-types-in-a-method-using-generics%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            4
















            In generic methods, the type is inferred by the compiler using the actual arguments. But your argument doesn't have any type T. You can send another parameter Class<T> to tell the type of the return value:



            public <T extends Root> T gets(int type, Class<T> c) 
            switch (type)
            case 1:
            return c.cast(new A());
            case 2:
            return c.cast(new B());
            default:
            throw new RuntimeException();




            But in your case you don't know the type before you call this method.



            So all you can do is make this method non-generic and change return type to just Root. Then you can do instanceof check to identify the class, perform casting, and then get the relevant fields.



            It doesn't make sense to make this method generic anyway, because generic methods can work with different type of supplied data. But in your case it's always an int. So I would say your method is not really generic.






            share|improve this answer






















            • 1





              That code is error prone and will cause ClassCastException

              – Sean F
              Mar 28 at 14:33











            • @SeanF I agree. But if the OP was actually going to use it, I would do a c.equals(A.class) check.

              – Kartik
              Mar 28 at 23:14















            4
















            In generic methods, the type is inferred by the compiler using the actual arguments. But your argument doesn't have any type T. You can send another parameter Class<T> to tell the type of the return value:



            public <T extends Root> T gets(int type, Class<T> c) 
            switch (type)
            case 1:
            return c.cast(new A());
            case 2:
            return c.cast(new B());
            default:
            throw new RuntimeException();




            But in your case you don't know the type before you call this method.



            So all you can do is make this method non-generic and change return type to just Root. Then you can do instanceof check to identify the class, perform casting, and then get the relevant fields.



            It doesn't make sense to make this method generic anyway, because generic methods can work with different type of supplied data. But in your case it's always an int. So I would say your method is not really generic.






            share|improve this answer






















            • 1





              That code is error prone and will cause ClassCastException

              – Sean F
              Mar 28 at 14:33











            • @SeanF I agree. But if the OP was actually going to use it, I would do a c.equals(A.class) check.

              – Kartik
              Mar 28 at 23:14













            4














            4










            4









            In generic methods, the type is inferred by the compiler using the actual arguments. But your argument doesn't have any type T. You can send another parameter Class<T> to tell the type of the return value:



            public <T extends Root> T gets(int type, Class<T> c) 
            switch (type)
            case 1:
            return c.cast(new A());
            case 2:
            return c.cast(new B());
            default:
            throw new RuntimeException();




            But in your case you don't know the type before you call this method.



            So all you can do is make this method non-generic and change return type to just Root. Then you can do instanceof check to identify the class, perform casting, and then get the relevant fields.



            It doesn't make sense to make this method generic anyway, because generic methods can work with different type of supplied data. But in your case it's always an int. So I would say your method is not really generic.






            share|improve this answer















            In generic methods, the type is inferred by the compiler using the actual arguments. But your argument doesn't have any type T. You can send another parameter Class<T> to tell the type of the return value:



            public <T extends Root> T gets(int type, Class<T> c) 
            switch (type)
            case 1:
            return c.cast(new A());
            case 2:
            return c.cast(new B());
            default:
            throw new RuntimeException();




            But in your case you don't know the type before you call this method.



            So all you can do is make this method non-generic and change return type to just Root. Then you can do instanceof check to identify the class, perform casting, and then get the relevant fields.



            It doesn't make sense to make this method generic anyway, because generic methods can work with different type of supplied data. But in your case it's always an int. So I would say your method is not really generic.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 28 at 4:21

























            answered Mar 28 at 3:36









            KartikKartik

            5,4613 gold badges19 silver badges39 bronze badges




            5,4613 gold badges19 silver badges39 bronze badges










            • 1





              That code is error prone and will cause ClassCastException

              – Sean F
              Mar 28 at 14:33











            • @SeanF I agree. But if the OP was actually going to use it, I would do a c.equals(A.class) check.

              – Kartik
              Mar 28 at 23:14












            • 1





              That code is error prone and will cause ClassCastException

              – Sean F
              Mar 28 at 14:33











            • @SeanF I agree. But if the OP was actually going to use it, I would do a c.equals(A.class) check.

              – Kartik
              Mar 28 at 23:14







            1




            1





            That code is error prone and will cause ClassCastException

            – Sean F
            Mar 28 at 14:33





            That code is error prone and will cause ClassCastException

            – Sean F
            Mar 28 at 14:33













            @SeanF I agree. But if the OP was actually going to use it, I would do a c.equals(A.class) check.

            – Kartik
            Mar 28 at 23:14





            @SeanF I agree. But if the OP was actually going to use it, I would do a c.equals(A.class) check.

            – Kartik
            Mar 28 at 23:14













            0
















            The method indicates that there is a T that extends Root which is the return type. However, until the method is used somewhere, you don't know which class that is. You don't know if T will be A, or B, or something else. Each time it is used it will be exactly one subclass of Root.



            But here your code is assuming it will be both A and B at the same time. In fact, T might be neither. If T is A, you cannot return an instance of B. If T is B, you cannot return an instance of A. If T is neither A nor B, you cannot return either an instance of A or B.



            You have to return an instance of T.



            One thing you can do is not use generics and just return Root.






            share|improve this answer





























              0
















              The method indicates that there is a T that extends Root which is the return type. However, until the method is used somewhere, you don't know which class that is. You don't know if T will be A, or B, or something else. Each time it is used it will be exactly one subclass of Root.



              But here your code is assuming it will be both A and B at the same time. In fact, T might be neither. If T is A, you cannot return an instance of B. If T is B, you cannot return an instance of A. If T is neither A nor B, you cannot return either an instance of A or B.



              You have to return an instance of T.



              One thing you can do is not use generics and just return Root.






              share|improve this answer



























                0














                0










                0









                The method indicates that there is a T that extends Root which is the return type. However, until the method is used somewhere, you don't know which class that is. You don't know if T will be A, or B, or something else. Each time it is used it will be exactly one subclass of Root.



                But here your code is assuming it will be both A and B at the same time. In fact, T might be neither. If T is A, you cannot return an instance of B. If T is B, you cannot return an instance of A. If T is neither A nor B, you cannot return either an instance of A or B.



                You have to return an instance of T.



                One thing you can do is not use generics and just return Root.






                share|improve this answer













                The method indicates that there is a T that extends Root which is the return type. However, until the method is used somewhere, you don't know which class that is. You don't know if T will be A, or B, or something else. Each time it is used it will be exactly one subclass of Root.



                But here your code is assuming it will be both A and B at the same time. In fact, T might be neither. If T is A, you cannot return an instance of B. If T is B, you cannot return an instance of A. If T is neither A nor B, you cannot return either an instance of A or B.



                You have to return an instance of T.



                One thing you can do is not use generics and just return Root.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 28 at 4:47









                Sean FSean F

                2,1966 silver badges14 bronze badges




                2,1966 silver badges14 bronze badges
























                    0
















                    You can modify your method as below by casting to T.



                     public <T extends Root> T gets(int type) 
                    switch (type)
                    case 1:
                    return (T) new A();
                    case 2:
                    return (T) new B();
                    default:
                    throw new RuntimeException();







                    share|improve this answer

























                    • That is error prone and will cause ClassCastException

                      – Sean F
                      Mar 28 at 14:32















                    0
















                    You can modify your method as below by casting to T.



                     public <T extends Root> T gets(int type) 
                    switch (type)
                    case 1:
                    return (T) new A();
                    case 2:
                    return (T) new B();
                    default:
                    throw new RuntimeException();







                    share|improve this answer

























                    • That is error prone and will cause ClassCastException

                      – Sean F
                      Mar 28 at 14:32













                    0














                    0










                    0









                    You can modify your method as below by casting to T.



                     public <T extends Root> T gets(int type) 
                    switch (type)
                    case 1:
                    return (T) new A();
                    case 2:
                    return (T) new B();
                    default:
                    throw new RuntimeException();







                    share|improve this answer













                    You can modify your method as below by casting to T.



                     public <T extends Root> T gets(int type) 
                    switch (type)
                    case 1:
                    return (T) new A();
                    case 2:
                    return (T) new B();
                    default:
                    throw new RuntimeException();








                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 28 at 5:08









                    LeoNLeoN

                    1,3639 silver badges17 bronze badges




                    1,3639 silver badges17 bronze badges















                    • That is error prone and will cause ClassCastException

                      – Sean F
                      Mar 28 at 14:32

















                    • That is error prone and will cause ClassCastException

                      – Sean F
                      Mar 28 at 14:32
















                    That is error prone and will cause ClassCastException

                    – Sean F
                    Mar 28 at 14:32





                    That is error prone and will cause ClassCastException

                    – Sean F
                    Mar 28 at 14:32

















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55389681%2fhow-to-return-different-types-in-a-method-using-generics%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript