简体   繁体   中英

What is the equivalent Java keyword/construct for C#'s default()?

In C#, the default keyword sets a default value of a type parameter. This will be null for reference types and zero for value types.

I'm looking for an equivalent keyword or construct in Java. I'm very fuzzy on reference vs. value types in Java - do they behave the same?

I've got a function defined as

private T BuildEntityFromResultSet(ResultSet resultSet)
{
    // Initialize T appropriately
    T entity = <blank>; // default(T) in C#.
}

Is there a keyword to initialize T properly that can fill in the blank above? Is it necessary to be concerned about an initial value (other than null) in Java?

I saw this question , but it doesn't seem to answer mine.

This functionality is not needed in Java, since type parameters are erased at runtime, ie your field entity will be of type Object after compilation. Therefore you cannot have primitive types (what you call value types) as type parameters in Java at all. And the default value for all reference types is null .

There is no corresponding construct in Java. Primitive numbers are always defaulted to zero; boolean to false, and Objects to null. But Java have no value types.

With generics, this functionality can be avoided. Consider:

public Holder<T> {
  private T _value;
  public reset() {
    _value = ??
  }
}

Here, one cannot use Holder<int> , only Holder<Integer> , so _value can always be reset null.

I've found a place where this functionality is missed, however. If you are writing an InvocationHandler for a Java Proxy, and the method's return type is a primitive, simply returning null does not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM