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();
}
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