22

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.

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.

2
  • I think that this question is actually about Java reflection, but it's not actually clear. Jun 2, 2009 at 23:00
  • I don't see any static methods - funny yeah !
    – nanosoft
    Aug 29, 2018 at 7:01

4 Answers 4

40

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:

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");
0
35

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 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();
2
  • 2
    Eclipse (and quite possibly other IDEs) even offers to warn you if you're calling a static method using instance syntax ("Non-static access to static member", it's called). It's not an error, but it's a little less clear than using explicitly static access. Jun 2, 2009 at 23:19
  • 1
    I think Sun's compiler itself issues that warning, too, now. I believe it is confusing enough that it should be made an error: stackoverflow.com/questions/610458/…
    – Thilo
    Jun 3, 2009 at 0:37
16

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 someClass = SomeType.class;
Method staticMethod = someClass.getMethod( "methodName", ... );

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.