问题描述
说,我引用了一个Class对象,SomeType有一个静态方法。有没有办法调用该方法w / o实例化SomeType第一?
Say, I have a reference to a Class object with SomeType having a static method. Is there a way to call that method w/o instantiating SomeType first? Preferably not escaping strong typing.
编辑:好的,我搞砸了。
OK, I've screwed up.
interface Int{
void someMethod();
}
class ImplOne implements Int{
public void someMethod() {
// do something
}
}
Class<? extends Int> getInt(){
return ImplOne.class;
}
在这种情况下,someMethod >
In this case someMethod() can't be static anyways.
推荐答案
根据定义,一个静态方法在一个类上调用,而不是在该类的实例上调用。
A static method, by definition, is called on a class and not on an instance of that class.
所以如果你使用:
SomeClass.someStaticMethod()
无需实例化(放弃类加载和实例化 SomeClass
类
you are instantiating nothing (leave aside the class loading and instantiation of the SomeClass
class itself, which the JVM handles and is way out of your scope).
这与在一个对象上调用的常规方法相反,它已经被实例化了:
This is opposed to a regular method called on an object, which has already been instantiated:
SomeObject o = someObject; // had to be instantiated *somewhere*
o.someMethod();
这篇关于在类上调用静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!