2

in C#, we can define a generic class A<T> where T : new(). In this code, we can create an instance of T with new T(). How does this implement in Java? I read some article which says it's impossible.

The reason that I used have a singleton patten using generic in C# like:

public static class Singleton<T> where T : new()
{
    private static T instance;

    public static T Instance
    {
        get 
        {
            if (instance == null)
            {
                instance = SingletonCreater.Instance;
            }
            return instance;
        }
    }

    static class SingletonCreater
    {
        internal static readonly T Instance = new T();
    }
}

And way to make this method more graceful?

1

3 Answers 3

7

No you can't do new T(), since you don't know if T has a no arg constructor, and because the type of T is not present at runtime due to type erasure.

To create an instance of T, you need to have code like,

public <T> T create(Class<T> clazz) {
    try {
        //T must have a no arg constructor for this to work 
        return clazz.newInstance(); 
    } catch (InstantiationException e) {
        throw new IllegalStateException(e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
}
Sign up to request clarification or add additional context in comments.

9 Comments

I see, so I cannot implement like the way I used in C#, right? We can keep this open and see if there is any other idea. :)
in c#, how do you know that T has a no arg constructor?
In the class definition, we have where T : new() which means this T accepts none-argument constructor :)
No-arg constructor is not an issue at all. Type erasure is.
In this part, MS' API is more powerful I think.
|
1

Yes, new T() is impossible as generic is a compile time feature in Java. During runtime the generic information is lost; therefore, you will not be able to do new T() since the JVM have no idea what T is during runtime.

You might be out of luck to use the exact syntax as you mentioned using Java.

Comments

0

Thank you guys, in all, we cannot use it in JAVA. As Sbridges' way, in C#, we can implement like this:

static T Create(Type type)
{
    return (T)Activator.CreateInstance(type);
}

or even easier:

static T Create()
{
    return Activator.CreateInstance<T>();
}

Just let you know.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.