Receiving a Java Method without using getDeclaredMethod - java

I wish to initialize an array of java methods in the child class, as a class field like so
void callme() {System.out.println("hi!");}
Method[] actions = new Method[] {&callme,&callme};
and call all methods in this array at parent class like so:
for (meth:actions) {meth.invoke();}
However currently I cannot find a way to implicitly initialize the actions array, not through the constructor. The following gives me an error due to unhandled exception:
Method[] actions = new Method[] {
this.getClass().getDeclaredMethod("count")
};
As said, I cannot catch the exception when initializing this array explicitly as a field, and not in the constructor.
I'm a newbie to java reflection, so this is probably an obvious question, still I found no answer to that at google, any help would be appreciated.
Thanks
P.S.
As Scott below guessed, I "want a superclass to call a specific set of methods defined in a subclass".

Are you sure reflection is the right thing to do? Normally an interface with several anonymous classes implementing it would be better style.
You can write an initializer block to be able to catch the exception during initialization.
Why don't you use getMethod()?

[Note: code below has not been compiled but should get the idea across]
I should echo -- what are you trying to accomplish?
If you want a superclass to call a specific set of methods defined in a subclass, you can do a few things.
With reflection, I'd recommend using annotations:
1) define an annotation HeySuperclassCallMe (make sure retention is RUNTIME)
2) annotate the methods to call with HeySuperclassCallMe
#HeySuperclassCallMe public void foo...
3) in your superclass do something like
for (Method m : getClass().getMethods())
if (m.getAnnotation(HeySuperclassCallMe.class) != null)
m.invoke(...)
That's a nice reflective means to do it.
For non-reflection (which should be a bit faster, but more code):
1) define an interface that represents the calls
public interface Call {
void go();
}
2) in your superclass, define a
private List<Call> calls
protected void addCall(Call call)
3) in the subclass, use addCall:
addCall(new Call() {public void go() {foo();}} );
4) in the superclass
for (Call call : calls)
call.go();

Check out the Apache Commons - Beanutils! It's like a wrapper around all the reflection which is very easy to use. It wraps method invocation, modify attributes, lookups...
If you want to bring in dynamic to Java, you should have a look a dynamic JVM languages which can be used by simple including a .jar library! On of them is Groovy which contains the java syntax and bring in a lot of dynamic functionality (scripting, rapid-prototyping, Meta-Object-Protocol, runtime-method repacement, dynamic proxies...).

This should work as long, as your method is really declared in in the this.getClass().
If it is inherited, you should use Class.getMethod() instead.
However, instead of using function pointers, in java one would define an interface with a method one want to call, and let that interface be implemented by the target object.
Also consider using ArrayList, or other collection classes instead of arrays.

I can tell by your ampersands that you are thinking in C. We don't really use pointers to functions in java.
Generally, you would not use java reflection for this. As one of the other posters said - you would create an interface, and have objects that implemented that interface - either by directly implementing it, or with an adapter or anonymous class:
interface Callable { void callme(); }
Callable[] foo = new Callable[] {
new Callable() { public void callme() {System.out.println("foo!");}},
new Callable() { public void callme() {System.out.println("bar!");}}
};
for(Callable c: foo) {
c.callme();
}

Create a static method in your class which will return an array of declared methods and do the correct handling of exceptions.
private static Method[] declaredMethods(Class<T> clazz, String methodName) {
Method[] result = new Method[1];
try{
result[0] = clazz.getDeclaredMethod(methodName);
} catch (NoSuchMethodException nsme) {
// respond to the error
} catch (SecurityException se) {
// Respond to the error
}
return result;
}
Method[] actions = declaredMethods("count");

Related

Questions on classes extending from a base class (Java)

I'm a beginner in Java trying to write a system of party quests for a game that I'm currently writing and I have a few questions I'd like to be answered. I've already gone around and asked other people, but they're not familiar in Java.
In the past I'd tried making a bunch of classes and accessing them with multiple get methods. I found that incredibly tedious to write and thought I could unify them under an abstract class/implemented class. Thus, the code looked more like this ...
DynastyPQInterface pq = new CustomPQ // or ....
DynastyPQInterface pq = new OtherCustomPQ
Of course, this presented difficulties such as being only able to use implemented methods. It didn't allow me to access the class' exclusive methods that I might want to use later on.
Ultimately, what I want to do is to be able to use a single get method to return any of these derived classes, but still retain the ability to just universally use the get method to call methods that they have in common, such as execute, create, end, while simultaneously allowing me to reach out to their exclusive methods specifically. Is there a way to do that, or is it impossible?
If it's still not clear ...
The code I have write now is a base class that is extended to the other classes in the manner ...
DynastyPQ (base) -> methods include (run(), execute(), end())
CustomAPQ (inherited from DynastyPQ) -> (has exclusive methods like getPoints())
CustomBPQ (inherited from DynastyPQ) -> (has exclusive methods like revivePlayer())
I want to write a get method so to rid myself of multiple. What I have right now is ...
DynastyPQ dynastyPQ;
DynastyPQ getPQ() {
return dynastyPQ;
}
void setPQ(DynastyPQ pq) {
dynastyPQ = pq;
}
Doing this ...
DynastyPQ pq = new CarnivalPQ();
I can only access DynastyPQ's methods rather than Carnival's methods.
Is there a way to access the exclusive methods while universally being able to execute the four base functions without regard to the type of class, or did I miss something earlier?
tl;dr -> I want one get method that universally returns all classes that inherit from class X; however, I want to be able to access each class's exclusive methods.
You can probably just cast the object to the derived class:
DynastyPQ pq = new CustomAPQ();
((CustomAPQ)pq).customAPQmethod();
If you don't know what is the dynamic type (the type you used after the new operator), you can use the instanceof keyword:
DynastyPQ pq = getPQ();
if (pq instanceof CustomAPQ) {
CustomAPQ a = (CustomAPQ)pq;
a.customAPQmethod();
} else if (pq instanceof CustomBPQ) {
CustomBPQ b = (CustomBPQ)pq;
b.customBPQmethod();
} else {
// Neither a CustomAPQ nor a CustomBPQ.
}
If you don't want to do that, you can use polymorphism:
class DynastyPQ {
final void run() {
// code.
}
final void execute() {
// code.
}
final void create() {
// code.
}
void specific1() {}
void specific2() {}
}
class CustomAPQ extends DynastyPQ {
#Override
void specific1() {
// do stuff specific to CustomAPQ.
}
#Override
void specific2() {
// do stuff specific to CustomAPQ.
}
}
class CustomBPQ extends DynastyPQ {
#Override
void specific1() {
// do stuff specific to CustomBPQ.
}
#Override
void specific2() {
// do stuff specific to CustomBPQ.
}
}
Now, you can do:
DynastyPQ pq = new CustomAPQ();
pq.specific1();
The called method will be CustomAPQ::specific1(). If specific1() was not declared in CustomAPQ, then, it will just do nothing.
Other than #CelineNOEL suggested it is not possible. Because you declared a class of type DynastyPQ, you can call only methods defined inside that class. In the moment you want to call specific method, not shared one, you know from which class it is and you can use casting to call that specific method.
((CustomAPQ)pq).customAPQmethod()
Shared methods you are using in code, when you don't know which class should execute same peace of code(or you want it to execute it different if you override share methods in every sub-class), and you delegate it to be resolved in runtime. So reconsider your design and in base class put methods that needs to be called dynamically. All other methods you are sure are specific for one class put only in that class. On that way your code will be cleaner and you will not mess thing that should be separated.

Can we write a function in Java that takes another function signature as a parameter and executes it? [duplicate]

This may be something common and trivial, but I seem to be having trouble finding a concrete answer. In C# there is a concept of delegates, which relates strongly to the idea of function pointers from C++. Is there a similar functionality in Java? Given that pointers are somewhat absent, what is the best way about this? And to be clear, we're talking first class here.
The Java idiom for function-pointer-like functionality is an an anonymous class implementing an interface, e.g.
Collections.sort(list, new Comparator<MyClass>(){
public int compare(MyClass a, MyClass b)
{
// compare objects
}
});
Update: the above is necessary in Java versions prior to Java 8. Now we have much nicer alternatives, namely lambdas:
list.sort((a, b) -> a.isGreaterThan(b));
and method references:
list.sort(MyClass::isGreaterThan);
You can substitue a function pointer with an interface. Lets say you want to run through a collection and do something with each element.
public interface IFunction {
public void execute(Object o);
}
This is the interface we could pass to some say CollectionUtils2.doFunc(Collection c, IFunction f).
public static void doFunc(Collection c, IFunction f) {
for (Object o : c) {
f.execute(o);
}
}
As an example say we have a collection of numbers and you would like to add 1 to every element.
CollectionUtils2.doFunc(List numbers, new IFunction() {
public void execute(Object o) {
Integer anInt = (Integer) o;
anInt++;
}
});
You can use reflection to do it.
Pass as parameter the object and the method name (as a string) and then invoke the method. For example:
Object methodCaller(Object theObject, String methodName) {
return theObject.getClass().getMethod(methodName).invoke(theObject);
// Catch the exceptions
}
And then use it as in:
String theDescription = methodCaller(object1, "toString");
Class theClass = methodCaller(object2, "getClass");
Of course, check all exceptions and add the needed casts.
No, functions are not first class objects in java. You can do the same thing by implementing a handler class - this is how callbacks are implemented in the Swing etc.
There are however proposals for closures (the official name for what you're talking about) in future versions of java - Javaworld has an interesting article.
This brings to mind Steve Yegge's Execution in the Kingdom of Nouns. It basically states that Java needs an object for every action, and therefore does not have "verb-only" entities like function pointers.
To achieve similar functionality you could use anonymous inner classes.
If you were to define a interface Foo:
interface Foo {
Object myFunc(Object arg);
}
Create a method bar which will receive a 'function pointer' as an argument:
public void bar(Foo foo) {
// .....
Object object = foo.myFunc(argValue);
// .....
}
Finally call the method as follows:
bar(new Foo() {
public Object myFunc(Object arg) {
// Function code.
}
}
Java8 has introduced lambdas and method references. So if your function matches a functional interface (you can create your own) you can use a method reference in this case.
Java provides a set of common functional interfaces. whereas you could do the following:
public class Test {
public void test1(Integer i) {}
public void test2(Integer i) {}
public void consumer(Consumer<Integer> a) {
a.accept(10);
}
public void provideConsumer() {
consumer(this::test1); // method reference
consumer(x -> test2(x)); // lambda
}
}
There is no such thing in Java. You will need to wrap your function into some object and pass the reference to that object in order to pass the reference to the method on that object.
Syntactically, this can be eased to a certain extent by using anonymous classes defined in-place or anonymous classes defined as member variables of the class.
Example:
class MyComponent extends JPanel {
private JButton button;
public MyComponent() {
button = new JButton("click me");
button.addActionListener(buttonAction);
add(button);
}
private ActionListener buttonAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// handle the event...
// note how the handler instance can access
// members of the surrounding class
button.setText("you clicked me");
}
}
}
I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.
How It Works
We have a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.
With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.
In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array did not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to it's inner workings.
The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.
Check the closures how they have been implemented in the lambdaj library. They actually have a behavior very similar to C# delegates:
http://code.google.com/p/lambdaj/wiki/Closures
Relative to most people here I am new to java but since I haven't seen a similar suggestion I have another alternative to suggest. Im not sure if its a good practice or not, or even suggested before and I just didn't get it. I just like it since I think its self descriptive.
/*Just to merge functions in a common name*/
public class CustomFunction{
public CustomFunction(){}
}
/*Actual functions*/
public class Function1 extends CustomFunction{
public Function1(){}
public void execute(){...something here...}
}
public class Function2 extends CustomFunction{
public Function2(){}
public void execute(){...something here...}
}
.....
/*in Main class*/
CustomFunction functionpointer = null;
then depending on the application, assign
functionpointer = new Function1();
functionpointer = new Function2();
etc.
and call by
functionpointer.execute();

How do I reduce delegation boilerplate?

I have a class that implements an interface. There's another class that implements this interface, too, and an instance of this second class backs my class's implementation.
For many of the methods specified by the interface, my class simply forwards them straight to the second class.
public class MyClass implements MyInterface
{
private OtherClass otherClassInstance; // Also implements MyInterface.
// ...
void foo() { otherClassInstance.foo(); }
void bar() { otherClassInstance.bar(); }
void baz() { otherClassInstance.baz(); }
// ...
}
Simply deriving my class from the second class would eliminate all of this, but it doesn't make sense because the two classes are unrelated to each other (besides implementing a common interface). They represent different things - it just so happens that a lot of my class's implementation copies that of the other class. In other words, my class is implemented atop the second class, but it is not itself a subset of the second class. As we know, inheritance is meant to express an "is-a" relationship, not to share implementation, so it's inappropriate in this case.
This portion of a talk by Joshua Bloch illustrates the situation well.
I know that Java doesn't have any language support for delegation. However, is there at least some way to clean up my class's implementation so it isn't so redundant?
An answer which is not really an answer to your actual question:
I'd say, live with the boilerplate. Let IDE generate it for you. Example: in Netbeans, add the private ArrayList field, set cursor to where you'd want the methods to appear, hit alt-insert, select "Generate Delegate Method...", click the methods you want to create a delegate for in the dialog opens, submit, go through the generated methods and make them do the right thing, you're done.
It is a bit ugly, but it is still preferable to starting to mess with reflection, when you are dealing with just one class, like it sounds. Your class is probably the kind of class, which you will complete and fully test, and then hopefully never touch again. Reflection creates runtime cost which does not go away. Suffering the auto-generated boilerplate in the source file is probably preferable in this case.
First way to use http://java.sun.com/javase/6/docs/api/java/lang/reflect/Proxy.html see tutorial http://docs.oracle.com/javase/1.4.2/docs/guide/reflection/proxy.html
Second way using AOP you can create dispatcher that intercept all invocation of specific class
For both ways you need to manage methods processing using reflection API
EDITED TO SHOW IDEA
Following code taken from tutorial above just modified a little (see youListImpl.getRealArrayList() in invoke method)
public class DebugProxy implements java.lang.reflect.InvocationHandler {
private YouListImpl youListImpl;
public static Object newInstance(Object obj) {
return java.lang.reflect.Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
new DebugProxy(obj));
}
private DebugProxy(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method m, Object[] args)
throws Throwable
{
Object result;
try {
System.out.println("before method " + m.getName());
result = m.invoke(youListImpl.getRealArrayList(), args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " +
e.getMessage());
} finally {
System.out.println("after method " + m.getName());
}
return result;
}
}

Code using classes and interfaces

I'm new to Java, but I understand the basics. I know that interfaces are abstract classes and they're used for emulating multiple inheritance (kind of - I know that in Java this is not allowed). I have this code; would you explain it to me?
Here is part of a method that iterates over a list of classes:
Constructor[] c = aClass.getConstructors();
for (Constructor constructor : c) {
if (constructor.getParameterTypes().length == 0) {
AInterface action = (AInterface) constructor.newInstance();
try {
action.run(request, response);
}
}
}
Here is the interface definition used by the above code:
public interface AInterface
{
void run(HttpServletRequest request, HttpServletResponse response);
}
It uses reflection to create an instance of the class whose java.lang.Class object is stored in the aClass variable, using it's zero-argument constructor (if it has one), and then calls one of its methods (it is assumed to implement AInterface).
That code looks like it's from some web framework. Why are you looking at it? Reflection is one of the more advanced things about Java, not something that beginners usually need to deal with.
For what is calling the method run, if the method run hasn't a body? For what is good?
The class which is created (aClass) is a concrete class, not an interface, and it will implement the interface and contain the body of the run method. You need to learn more about interfaces (Google is your friend).
It's looking for a 0-argument constructor for the class AClass. There will not be more than one. :)
It then creates an instance of that class using that constructor.
It then calls the "run" method of that class with two objects.
Hope this helps.
Constructor[] c = aClass.getConstructors(); // Retrieve all the constructors
// of the class 'aClass'
for (Constructor constructor : c) { // Iterate all constructors
// Until the only default constructor is found.
if (constructor.getParameterTypes().length == 0) {
// Create a new instance of 'aClass' using the default constructor
// Hope that 'aClass' implements 'AInterface' otherwise ClassCastException ...
AInterface action = (AInterface) constructor.newInstance();
try {
// action has been cast to AInterface - so it can be used to call the run method
// defined on the AInterface interface.
action.run(request, response);
} // Oops - missing catch and/or finally. That won't compile
}
}
// Missing a bit of error handling here for the countless reflection exception
// Unless the method is declared as 'throws Exception' or similar
Example of usage:
You have a class somewhere called 'TheClass'
public class TheClass implements AInterface {
public void run(HttpServletRequest request, HttpServletResponse response) {
System.out.println("Hello from TheClass.run(...)");
// Implement the method ...
}
}
Somewhere in the application, either using Reflection or reading a Configuration file.
The application finds out that it should execute 'TheClass'.
You do not have any indication about 'TheClass' other that it should implement AInterface and it has an default constructor.
You can create the Class object using
Class aClass = Class.forName("TheClass");
and use 'aClass' in you previous code snippet (after adding the code for errorhandling). You should see in the console
Hello from TheClass.run(...)

Java Methods - Taking a method AS AN ARGUMENT

I've come across some code that I can't share here but it declares a method WITHIN the paramter list of another method. I didnt even know that was possible. I dont really understand why its doing that. Can someone please explain to me some possible uses that you as a programmer would have for doing that? (Note: Since I can't show the code I dont expect an in-context explanation just generally)
Related:
What's the nearest substitute for a function pointer in Java?
Did the code look something like this?
obj.someMethod(myVar,3,new FooObject() {
public void bar() {
return "baz";
}
});
If so, then the method is not being passed to the other method as an argument, but rather an anonymous inner class is being created, and an instance of that class is being passed as the argument.
In the example above FooObject is an abstract class which doesn't implement the bar() method. Instead of creating a private class that extends FooObject we create an instance of the abstract class and provide the implementation of the abstract method in line with the rest of the code.
You can't create an instance of an abstract class so we have to provide the missing method to create a complete class defintion. As this new class is created on the fly it has no name, hence anonymous. As it's defined inside another class it's an anonymous inner class.
It can be a very handy shortcut, especially for Listener classes, but it can make your code hard to follow if you get carried away and the in line method definitions get too long.
In Java you can't pass methods as parameters. Could it have been passing not a method, but an anonymnous inner class?
This can be useful for passing behaviours between classes. Google "dependency injection" or "Inversion of control" for more information.
Have you ever seen the Functional Java?
It's a very interesting library that allows you programing like you would do in Scala.
I Wrote about this libs. I confess it is better to use in a more flexible syntax (BGGA closures) like Scala.
Using Functional Java with a high-order function like map on a list we have:
final List<Integer> numbers = list(1, 2, 3, 4, 5);
List<Integer> c = numbers.map(new F<Integer, Integer>() {
public Integer f(Integer arg) {
return arg * arg;
}
});
Another useful lib is lambdaj that offers nice ways to play like in Functional (FP) Programming.
Java has a limited syntax compared to FP languages. But you can still take some advantages of FP style, but you must be creative!
using java.lang.reflect.Method
example
public void callMethod(Method aMethod, int value) throws Exception {
aMethod.invoke(this, value);
}
public void print(Integer value) {
System.out.print(value);
}
public void println(Integer value) {
System.out.println(value);
}
public void demo() throws Exception {
Method println = this.getClass().getMethod("println", Integer.class);
Method print = this.getClass().getMethod("print", Integer.class);
callMethod(println, 10);
callMethod(print, 10);
}
The nearest thing to passing a function pointer in Java is passing an anonymous instance of an abstract class or interface. For example, a generic function type can be encoded in an interface like this:
public interface F<A, B> {
public B f(final A a);
}
You can then expect a method in another method's argument list:
public List<B> map(List<A> as, F<A, B> f) {
...
}
And you can call it with an anonymous instance of that interface:
map(myList, new F<Integer, String>() {
public String f(Integer i) {
return String.valueOf(i);
}
});
There's a library called Functional Java that exploits exactly this idea for great benefit glorious language Java.
It's not, per se, legal syntax in Java. Was it perhaps creating a new instance of an anonymous class?
You can also do something like this:
final Predicate somePredicate = new Predicate<Item>()
{
#Override
public boolean apply(Item item)
{
return item.someProperty().equals(something);
}
}
And use it like this:
List<Item> filteredList = filter(list, somePredicate);
I've done stuff like that before. I've also written methods that use a closure to build and return an anonymous implementation of an interface in a similar way:
Predicate isSomeColor(final Color color)
{
return new Predicate<Shape>()
{
#Override
public boolean apply(Shape shape)
{
return shape.getColor().equals(color);
}
}
}
List<Shape> redShapes = filter(shapes, isSomeColor(Color.RED);
All of this is still anonymous inner classes. Nowhere am I actually naming the class itself, I just have a reference to an instance of the class.
this is called reflection. there is a whole library of objects representing stuff like constructors, methods and such.
you can use it, for instance, in order to call a dynamic method that is determined on runtime.
Yes, declaration of a method within the parameter list of another method can be done. You can check out java.lang.reflect.Method
Using reflection, you retrieve a Method object representing the method you wish to pass as a parameter. Then you can call Method to invoke to make a call to that method.
Moreover, you can refer "Functional programming in the Java language" (http ://www.ibm.com/developerworks/java/library/j-fp.html) which can give you inside-out with examples.
The answers above are varying as to whether or not it is even possible. Is it possible through reflection? Is possible through the use of an anonymous inner class? We need to clarify this.
the closest to a function argument is
an instance of a anonymous class with exactly one method.
Runnable a = new Runnable(){
run(){
System.out.println("hello");
}
}
myMethod(a);
not pointer, but still you can write functions inline with some trick.
check my answer on another thread

Categories