meaninglessdisplayname
meaninglessdisplayname

Reputation: 746

Java equivalent of PHP's call_user_func()

What I'm trying to do is calling methods/objects with string variables.

I've got 'foo' and 'bar' and need to do foo.bar()

Is there something like PHP's call_user_func()? Any other suggestions?

Upvotes: 2

Views: 1369

Answers (4)

Joop Eggen
Joop Eggen

Reputation: 109597

If you have Interfaces that the class implements, then you can create a proxy class with a generic method handling. But that is even more specific than reflection.

Upvotes: 0

moonwave99
moonwave99

Reputation: 22812

There is no totally equivalent function in theory, because Java is pure OOP, and thus it doesn't provide a global scope function caller - which by the way is a crappy intent of replicating reflection itself, being PHP functions not proper objects at the time.

As already stated, you can use Java's reflection, which behaves like PHP's.

TL;DR

You can emulate call_user_func* stuff with Java reflection classes [Class, Method, Field].

Upvotes: 0

Yogendra Singh
Yogendra Singh

Reputation: 34367

It's called reflection in Java: Refer this tutorial for details.

     foo fooObject = new foo(); //not using reflection, but you can if you need to

     //use reflection on your class()not object to get the method
     Method method = foo.class.getMethod("bar", null);

     //Invoke the method on your object(not class)
     Object bar = method.invoke(fooObject, null);

As a side note: You class names shoul start with UpperCase e.g. Foo.

Upvotes: 1

Peter Butkovic
Peter Butkovic

Reputation: 12179

In java you should use reflection.

official documentation: http://docs.oracle.com/javase/tutorial/reflect/index.html

your case could look like this:

Class<?> c = Class.forName("foo");
Method  method = c.getDeclaredMethod ("bar", new Class [0] );
method.invoke (objectToInvokeOn, new Object[0]);

where objectToInvokeOn is the instance/object (of class foo) you want to call on. In case you have it.

Otherwise you should go for:

Class<?> c = Class.forName("foo");
Object objectToInvokeOn = c.newInstance();
Method  method = c.getDeclaredMethod ("bar", new Class [0] );
method.invoke (objectToInvokeOn, new Object[0]);

Upvotes: 1

Related Questions