Generic method in Java without generic argument

前端 未结 5 2077
无人共我
无人共我 2020-12-02 13:32

In C# I can do actually this:

//This is C#
static T SomeMethod() where T:new()
{
  Console.WriteLine(\"Typeof T: \"+typeof(T));
  return new T();
}
         


        
5条回答
  •  死守一世寂寞
    2020-12-02 13:47

    The current answer is safer but is technically outdated because in java7 and beyond you don't need the "Class clazz" argument. The type is inferred from the expected return type. You just get a warning about unsafe cast.

    public class Main {
    
        private static class Dog {
            public String toString() { return "dog"; }
        }
    
        private static class Cat {
            public String toString() { return "cat"; }
        }
    
        public static void main(String[] args) {
            Cat cat = parse("cat");
            Dog dog = parse("dog");
            System.out.println("the cat object is a " + cat);
            System.out.println("the dog object is a " + dog);
        }
    
        private static Object untypedParse(String stringToParse) {
            if(stringToParse.equals("dog")) {
                return new Dog();
            } else if(stringToParse.equals("cat")) {
                return new Cat();
            } else {
                throw new RuntimeException("not expected");
            }
        }
    
        public static  T parse(String stringToParse) {
            return (T)untypedParse(stringToParse);
        }
    
    }
    
    
    ~/test/generics$ javac Main.java
    Note: Main.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    ~/test/generics$ java Main
    the cat object is a cat
    the dog object is a dog
    

提交回复
热议问题