user243174
user243174

Reputation:

Generic Type to be of class type only in java

C# code:

public class XYZ<T> where T : class, new()

In .net you can force the generic to be of class type using the above syntex.

My Question is that how we can achieve the same using Java?

Upvotes: 1

Views: 134

Answers (3)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

Java does not have this special case. Typically you would do the standard thing of using an Abstract Factory.

Constraining the type to have a particular constructor is a static issue, and therefore erasure/reification is not necessary to implement it.

Upvotes: 0

Cam
Cam

Reputation: 15234

You can't do that. And why would you want to? You can't call new on any object t declared as T t anyway. Can you explain why you would want to do this?

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039140

In Java there's no constraint which allows you to express that the type must have a no-arg constructor. Contrary to .NET in Java T is erased at runtime.

Upvotes: 1

Related Questions