java 为什么 getClass() 不能用作静态方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5733427/
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:31:48  来源:igfitidea点击:

Why isn't getClass() available as a static method?

javastatic

提问by Jason S

In static contexts, how come you can't call a static version of getClass()(rather than having to use my.package.name.MyClassName.class) ?

在静态上下文中,为什么不能调用getClass()(而不是必须使用my.package.name.MyClassName.class)的静态版本?

Isn't the compiler smart enough to determine when to use object methods + when to use static methods?

编译器是否足够聪明来确定何时使用对象方法 + 何时使用静态方法?



NOTE for clarity:

为清楚起见,请注意:

I'm not saying that a static getClass()should be used insteadof the non-static method getClass()(that's kind of obvious -- if SpecialFoois a subclass of Foo, then the getClass()of a Foocould return Foo.classor SpecialFoo.classor something else and it has to be determined at runtime).

我不是说,一个static getClass()应该使用替代的非静态方法getClass()(这是一种明显的-如果SpecialFoo是的子类Foo,那么getClass()一个Foo可以返回Foo.classSpecialFoo.class或别的东西,它有在运行时确定)。

I'm saying that I'm wondering why aren't there twoversions of getClass(), one that is a static method which only applies in a static context, and the regular non-static method getClass(). If it's not possible, then it's not possible, and that's the answer. If it's possible but just hasn't been done, then it's a historical choice, and maybe there's a good reason for it. That's what I'd like to know.

我是说我想知道为什么没有两个版本的getClass(),一个是仅适用于静态上下文的静态方法,另一个是常规的非静态方法getClass()。如果不可能,那就不可能,这就是答案。如果有可能但还没有完成,那么这是一个历史选择,也许有一个很好的理由。这就是我想知道的。

It would be great to declare

宣布会很棒

final static Logger logger = LoggerFactory.getLogger(getClass());

instead of

代替

final static Logger logger = LoggerFactory.getLogger(my.package.name.MyClass.class);

where the former could be copied verbatim from one class to the next, whereas the latter requires you to copy the class name in each file.

前者可以从一个类逐字复制到下一个类,而后者需要您复制每个文件中的类名。

采纳答案by ColinD

If nothing else, because it isn't legal to have both a staticand non-staticversion of a method (probably because it's legal, if discouraged, to call a staticmethod in a non-staticcontext).

如果不出意外,因为同时拥有一个方法的版本static和非static版本是不合法的(可能是因为static在非static上下文中调用方法是合法的,如果不鼓励的话)。

I also feel like such a method, while useful in the context of defining a logger or whatever, could be confusing in other contexts, such as when called from an instance method.

我也觉得这样的方法虽然在定义记录器或其他内容的上下文中很有用,但在其他上下文中可能会造成混淆,例如从实例方法调用时。

回答by alexsmail

You can use this idiom

你可以使用这个成语

    Class<?> cl=new Object(){}.getClass().getEnclosingClass();

For example:

例如:

static class Bar {
    public static void main(String[] args) {
        Class<?> cl=new Object(){}.getClass().getEnclosingClass();
        System.out.println(cl==Bar.class);  //will print true
    }
}

回答by Liv

Each object is an instance of a class in Java and no class can be an instance of another class! Which is why getClass() is not static as it only makes sense in the context of an object : you are trying to find for an object what class is it an instance of. If it was a static function, it can be called outside an object -- but it doesn't make sense to write

每个对象都是 Java 中一个类的实例,没有一个类可以是另一个类的实例!这就是为什么 getClass() 不是静态的,因为它只在对象的上下文中才有意义:您正在尝试为对象查找它是哪个类的实例。如果它是一个静态函数,它可以在对象外部调用——但写起来没有意义

String.getClass()

because you already know you're "asking" the String class!

因为您已经知道您在“询问” String 类!

回答by Jberg

getClass() provides a different functionality than the static .class. It's used to get the run time class of the instance it's called on.

getClass() 提供与静态 .class 不同的功能。它用于获取调用它的实例的运行时类。

Object o = new String();
o.getClass() // returns Class<String>    
Object.class // returns Class<Object>

回答by irreputable

You can implement one yourself. Get the stacktrace, and find the caller class.

你可以自己实现一个。获取堆栈跟踪,并找到调用者类。

Actually the logger lib could implemented that itself

实际上记录器库可以自己实现

static Logger logger = LoggerFactory.getLogger(); // auto detect caller class

回答by True Soft

Because if getClass()would be static, its code would have to be defined in one class - probably Object. There, you can't determine the callersclass and there isn't an object instance who calls it.

因为 ifgetClass()是静态的,它的代码必须在一个类中定义 - 可能是Object. 在那里,您无法确定调用者类,也没有调用它的对象实例。

Edit:

编辑:

It's not about the name; it could be very well getClass2(). I'm saying that if you define a static method, you can't know the class that calls it:

这与名字无关;可能会很好 getClass2()。我是说,如果你定义了一个静态方法,你就无法知道调用它的类:

public class Object {

    public static Class<?> getClass2() {
        return ...?
    }

}

回答by atamanroman

Wouldn't a static getClass()method return the class object the class the variable which holds the object is from? That would change the semantics of getClass(). Example:

静态getClass()方法不会返回类对象,即保存对象的变量所在的类吗?这将改变getClass(). 例子:

Interface foo = new FooImpl(); 
foo.getClass(); // returns Class<FooImpl> because the runtime type is FooImpl. 
                // If getClass() was static, it would return Class<Foo>.

回答by leonbloy

In addition of other answers (which explain why we can't make a static method with the same signature as the non-static 'getClass()' method), one would wonder if it would possible to have, say a static Class getStaticClass()so that, for example String.getStaticClass()would be equivalent to String.class. But, again, this method could not be a "normal" method Where would it be defined? in Object? Then how would this single method know what to return (String.class or Object.class) when it was called as String.getStaticClass() or Object.getStaticClass() ? Would it decide it in runtime ? No way.

除了其他答案(这解释了为什么我们不能创建一个与非静态“getClass()”方法具有相同签名的静态方法)之外,人们会想知道是否有可能有,比如static Class getStaticClass()这样,对于示例String.getStaticClass()将等效于String.class. 但是,同样,这个方法不能是一个“正常”的方法它在哪里定义?在对象?那么当这个单一方法被称为 String.getStaticClass() 或 Object.getStaticClass() 时,它如何知道返回什么(String.class 或 Object.class)?它会在运行时决定吗?没门。

A static method does not make sense because String.classis known (resolved) at compile time. The method has no reasonable thing to do at runtime; you'd have to do some compilation magic so that the result of that method call is actually resolved at compile time.

静态方法没有意义,因为String.class在编译时已知(已解决)。该方法在运行时没有合理的事情要做;您必须执行一些编译魔术,以便在编译时实际解决该方法调用的结果。