Tuesday, May 8, 2012

C# said, Java said: Generic instantiation

C# said

public class GenericDemo {
    public static void Main(string[] args) {
        First f = Everybody.Want<First>();
        System.Console.WriteLine(f);
    }
}


class Everybody {
    public static T Want<T>() where T : new() {
        return new T();
    }
}


class First {
 override public string ToString() {
  return "Hello";
 }
}

Java said

public class GenericDemo {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException  {
       First f = Person.Wants(First.class);
       System.out.println(f);
    }
}


class Person {
    public static <T> T Wants(Class<T> t) throws IllegalAccessException, InstantiationException {
        return t.newInstance();
    }
}


class First {
 @Override public String toString() {
  return "Hello";
 }
}

No comments:

Post a Comment