java 值为 null 的引用类型类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5712881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:25:54  来源:igfitidea点击:

Type of reference type with value null?

javanullreference-type

提问by Alan Escreet

According to: http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html
4.5.2 Variables of Reference Type
A reference type can hold a nullreference.

根据:http: //java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html
4.5.2 引用类型
的变量引用类型可以保存一个null引用。

Is it possible to retrieve the declared type of the reference type when the assigned value is null?

当赋值为 时,是否可以检索引用类型的声明类型null

Specifically, in a method that uses reflection, I wish the method to be null-safe and act on the original declared type (though I know the following code snippet doesn't work), for instance:

具体来说,在使用反射的方法中,我希望该方法是空安全的并且对原始声明的类型进行操作(尽管我知道以下代码片段不起作用),例如:

String referenceType = null;
MyReflectionClass.reflectionMethod(referenceType);
...
public static void reflectionMethod(Object referenceType) {
   Class<?> declaredType = referenceType.getClass();
}

I would not be averse to using generics to have type Tinstead of Objectas the declared parameter type, if necessary.

如有必要,我不会反对使用泛型来拥有类型T而不是Object作为声明的参数类型。

Edit:I know that .getClass()works on the instance, not the declared type. I was wondering if it was possible to ask the referencefor it's declared type. Since class hierarchies are static, there should be no problem to get that information.

编辑:我知道这.getClass()适用于实例,而不是声明的类型。我想知道是否可以询问它的声明 type引用。由于类层次结构是静态的,因此获取该信息应该没有问题。

Edit2:Here, the situation is made clear: Is Java "pass-by-reference" or "pass-by-value"?
Java is only pass-by-value, so even though a reference type is used, it is always handled as if the value (object instance) is passed (even though the internals only pass an object pointer). This means that Java doesn't actually have a reference type that knows about it's type (at least as far as the programmer is concerned), it's all in the value instances.
Therefore it is impossible to determine the type of any nullvalue.

Edit2:在这里,情况很清楚:Java 是“按引用传递”还是“按值传递”?
Java 只是按值传递,因此即使使用了引用类型,也总是像传递值(对象实例)一样处理它(即使内部仅传递对象指针)。这意味着 Java 实际上没有一个知道它的类型的引用类型(至少就程序员而言),它全部在值实例中。
因此无法确定任何null值的类型。

采纳答案by helloworld922

In a single word, no. It doesn't make a whole lot of sense to try to find the members of a null reference, though, since null implies the absence of anything. You're probably better off just dis-allowing null as an input, probably by throwing a NullPointerException.

一句话,没有。但是,尝试查找空引用的成员并没有多大意义,因为空意味着不存在任何东西。您最好禁止 null 作为输入,可能是通过抛出NullPointerException.

If you must handle null, perhaps the best way is to explicitly pass the class reference (or even better, a direct reference to the method in question).

如果您必须处理 null,也许最好的方法是显式传递类引用(或者甚至更好,直接引用相关方法)。

public static void reflectionMethod(Object param, Class<?> referenceType) // null is dis-allowed for referenceType
{
    // ... no need to try to back-track the type from an object
}

If you can only ever get the null value, it's difficult (impossible unless there are other constraints imposed) to do much better than having a very lucky guess.

如果您只能获得空值,则很难(除非施加其他约束,否则不可能)做得比非常幸运的猜测要好得多。

回答by Robin Green

You misunderstand. getClass()doesn't tell you the declared type of the variable, it tells you the type of the object, if there is one. And let's stop and take a step back for a minute - which variable would you be referring to, if it did that? The original variable? The method parameter? Any other variable that it passed through along the way? That would be total madness.

你误会了。getClass()不会告诉你变量的声明类型,它会告诉你对象的类型,如果有的话。让我们停下来退后一步 - 如果它这样做了,您会指的是哪个变量?原始变量?方法参数?它沿途通过的任何其他变量?那将是完全的疯狂。

回答by WhiteFang34

You can't find the declared type of a nullreference. Generics can't really help either, as they're erased at compile time. Some way or another you'll have to pass the type at runtime if you need to know it for the nullcase.

您找不到null引用的声明类型。泛型也无济于事,因为它们在编译时被删除。如果您需要了解这种null情况,则必须以某种方式在运行时传递类型。

回答by brain

No it is not. In your example you will get a null pointer exception when trying to call a method on the null reference referenceType.

不它不是。在您的示例中,当您尝试在空引用 referenceType 上调用方法时,您将收到空指针异常。

More specifically it is not possible because the concrete type is not neccesarily known at compile time, e.g. if I declare a reference of type Object and assign it to a String then your method should discover that the object is a String not an Object.

更具体地说,这是不可能的,因为在编译时不一定知道具体类型,例如,如果我声明一个 Object 类型的引用并将其分配给一个 String,那么您的方法应该发现该对象是一个 String 而不是 Object。

Object referenceType= new String("I'm a string");
MyReflectionClass.reflectionMethod(referenceType);
...
public static void reflectionMethod(Object referenceType) {
   Class<?> declaredType = referenceType.getClass(); // returns String.class
}

回答by Dakshinamurthy Karra

I am not sure this is helpful in your context, but you can use generics for achieving something similar - Java 1.5+ keeps type information for the subclass.

我不确定这在您的上下文中是否有帮助,但是您可以使用泛型来实现类似的目标 - Java 1.5+ 保留子类的类型信息。

package spikes;

import java.lang.reflect.ParameterizedType;

public class ReflectMethod {
    public abstract static class GenericType<T> {
        public Class typedClass() {
            ParameterizedType pType = (ParameterizedType) getClass().getGenericSuperclass();
            return (Class) pType.getActualTypeArguments()[0];
        }

        public void reflectMethod(T o) {
            System.out.println("Class: " + typedClass());
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        GenericType<String> gs = new GenericType<String>() {

        };
        gs.reflectMethod("");
    }
}