[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 203
  • Last Modified:

Have a Class object, and a static method within that class. How do i call that method from another class?

So I have a class, say myPackage.myClass, and within that class i have a static method.

Now - in another class, say myPackage.myOtherClass, i have a Class object that points to myClass. How do i call the static method of that class, within myOtherClass?
0
dannertb
Asked:
dannertb
  • 4
  • 3
  • 2
1 Solution
 
dannertbAuthor Commented:
Later edit: the method is not static.
0
 
sciuriwareCommented:
You can call a method:

by  class.method( );

or by

     object-reference.method( );

the first applies to static methods, the second to non-static methods,
although static methods are accessible that way.

All depends on the access: public-protected-package-private

;JOOP!
0
 
sciuriwareCommented:
And please adjust your writing: a reference does not point to a class but to an object.
A class object? do you mean a static reference?

public class MyClass  // Starts with a capital letter!
{
public static aStaticMethod(){ <statements> }
.....
}

public class MyOtherClass   // Starts with a capital letter!
{
     public static MyClass ref = .....;

     public someMethod()
     {
           ref.aStaticMethod();  // There you go!
     }
 }

;JOOP!
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
sciuriwareCommented:
  public someMethod()
     {
           ref.aStaticMethod();  // There you go!
     }

or:

   public someMethod()
     {
           MyClass.aStaticMethod();  // Ditto, NOT via a reference.
     }

;JOOP!
0
 
hoomanvCommented:
> i have a Class object that points to myClass. How do i call the static method of that class
Through reflection

Class c = MyClass.class;
Class[] parameterTypes = new Class[] {String.class, ...};
Method m = c.getMethod("method-name", parameterTypes);
Object result = m.invoke(null, arguments); // null since you are calling a static method
0
 
dannertbAuthor Commented:
Bravo hoomanv. The only one who understood the real problem.
0
 
dannertbAuthor Commented:
However the method is not static...
0
 
hoomanvCommented:
> However the method is not static...
So instead of null pass an instance reference to the invoke method.
You can construct an instance from Class object too
0
 
dannertbAuthor Commented:
Yeah, with newInstance().

Thanks.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 4
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now