Java 在类上调用静态方法?

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

Calling static method on a class?

javaclassstatic-methods

提问by yanchenko

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.

说,我有一个 Class 对象的引用,其中 SomeType 有一个静态方法。有没有办法在不先实例化 SomeType 的情况下调用该方法?最好不要逃避强类型。

EDIT: 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;
}

In this case someMethod() can't be static anyways.

在这种情况下, someMethod() 无论如何都不能是静态的。

采纳答案by Yuval Adam

A static method, by definition, is called on a class and not on an instance of that class.

根据定义,静态方法是在类上调用的,而不是在该类的实例上调用。

So if you use:

所以如果你使用:

SomeClass.someStaticMethod()

you are instantiating nothing (leave aside the class loading and instantiation of the SomeClassclass itself, which the JVM handles and is way out of your scope).

你什么都没有实例化(撇开SomeClass类本身的类加载和实例化,JVM 处理并且超出了你的范围)。

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();

回答by Alex Beardsley

I'm not sure exactly what the situation is, but if you're looking to execute the static method on a class without knowing the class type (i.e. you don't know it's SomeType, you just have the Class object), if you know the name and parameters of the method you could use reflection and do this:

我不确定具体是什么情况,但是如果您希望在不知道类类型的情况下对类执行静态方法(即您不知道它是 SomeType,您只有 Class 对象),如果您知道可以使用反射的方法的名称和参数,然后执行以下操作:

Class c = getThisClassObjectFromSomewhere();

//myStaticMethod takes a Double and String as an argument
Method m = c.getMethod("myStaticMethod", Double.class, String.class);
Object result = m.invoke(null, 1.5, "foo");

回答by Carl Manaster

Yes. That's what static methods are all about. Just call it. SomeType.yourStaticMethodHere().

是的。这就是静态方法的全部意义所在。就叫它。SomeType.yourStaticMethodHere()。

回答by JSB????

Since you talk about a Class object, I assume that you're interested in Java reflection. Here's a brief snippet that does what you're trying to do:

由于您谈论的是 Class 对象,因此我假设您对 Java 反射感兴趣。这是一个简短的片段,可以完成您要执行的操作:

Class someClass = SomeType.class;
Method staticMethod = someClass.getMethod( "methodName", ... );

// pass the first arg as null to invoke a static method
staticMethod.invoke( null, ... );