简体   繁体   English

C#的default()等效的Java关键字/构造是什么?

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

In C#, the default keyword sets a default value of a type parameter. 在C#中,默认关键字设置类型参数的默认值。 This will be null for reference types and zero for value types. 对于引用类型,该值为null;对于值类型,该值为零。

I'm looking for an equivalent keyword or construct in Java. 我正在寻找Java中的等效关键字或构造。 I'm very fuzzy on reference vs. value types in Java - do they behave the same? 我对Java中的引用类型和值类型非常模糊-它们的行为相同吗?

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? 是否有一个关键字可以正确地初始化T,可以填补上面的空白? Is it necessary to be concerned about an initial value (other than null) in Java? 是否有必要关注Java中的初始值(非null)?

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. 在Java中不需要此功能,因为在运行时会删除类型参数,即,编译后您的字段entity将为Object类型。 Therefore you cannot have primitive types (what you call value types) as type parameters in Java at all. 因此,在Java中,根本不能将基本类型(称为值类型)作为类型参数。 And the default value for all reference types is null . 并且所有引用类型的默认值为null

There is no corresponding construct in Java. Java中没有相应的构造。 Primitive numbers are always defaulted to zero; 原始数字始终默认为零; boolean to false, and Objects to null. 布尔值为false,对象为null。 But Java have no value types. 但是Java没有值类型。

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. 在这里,不能使用Holder<int> ,只能使用Holder<Integer> ,因此_value始终可以重置为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. 如果您正在为Java代理编写InvocationHandler,并且该方法的返回类型是原始类型,则仅返回null无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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