Rakim
Rakim

Reputation: 1107

Invoke a method of an object of type Class

I ll try to set it as simple as possible because it confuses me too.

I got a method returning an object of type Class i.e.

public Class foo(){...}

When I call this method I'm keeping the result in a variable of type Class i.e.

Class obj = new foo();

foo() can return many different classes BUT all of them contain the same method bar().

How can I invoke that method from my obj variable?

I tried obj.bar() but the IDE doesn't seem to like it. I get

Error:(59, 34) error: cannot find symbol method bar()

Upvotes: 0

Views: 1411

Answers (3)

enrico.bacis
enrico.bacis

Reputation: 31524

It seems like you want to group behaviors, that's what Java interfaces do:

interface Barer {
    String bar();
}

class Foo implements Barer {
    String bar() {
        return "I'm a Foo";
    }
}

class Fooz implements Barer {
    String bar() {
        return "I'm a Fooz";
    }
}

Then in you code you can have something like:

Barer obj;

if (something) {
    obj = new Foo();
} else {
    obj = new Fooz();
}

obj.bar()

It makes little sense in fact to store the return value of a constructor in a Class object.


If you really are in the case that you need a Class object (remember that it will just point to the Class, not to the instance you have created), you can use Java reflection:

Class obj = new foo();
Method method = obj.getDeclaredMethod("bar");
method.invoke(null);

Upvotes: 2

Vyncent
Vyncent

Reputation: 1205

if method foo() returns Class, it means it don't return actual instance of the objet on which you want to call bar() method, but the class itself, so it's not possible to call method bar() on Class as Class.class don't have a method bar.

In your code example there is some mistake

Class obj = new foo();

The keyword new mean you're creating a new instance of a class, not you're calling a method on an object.


In fact the right approach would be to use interfaces.

Instead of returning Class from foo method, declare an interface,

public interface MyInterface {
  public void bar();
}

and make foo() returning MyInterface instead of Class.

Then you can do

MyInterface obj = tmp.foo();
obj.bar()

Upvotes: 1

Antoniossss
Antoniossss

Reputation: 32535

If all returned values are objects of classes that implements the same method, you should declare that method in separate interface and let them implement it. Later on you can use generic wildcard like <? extends BarInterface> or change return type to BarInterface.

public interface BarInterface{
    public void bar();
}

and

public <T extends BarInterface> foo(){...}

or

public BarInterface foo() {...}

Upvotes: 0

Related Questions