How can I do ArrayList of Methods? - java

Is it posible in java?
void aaa(){}
ArrayList<Method> list = new ArrayList<Method>();
list.add(aaa);
If it isn't, how i can realize collection of methods (functions).
I want to get some method by ID.

You can do something like:
interface VoidFunction {
void evaluate();
}
...
List<VoidFunction> list = new ArrayList<>();
VoidFunction aaa = new VoidFunction() {
#Override
public void evaluate() {
aaa();
}
}
list.add(aaa);
In Java 8 this should be much easier and nicer:
List<Consumer<Void>> list = new ArrayList<>();
Consumer<Void> aaa = () -> {...};
list.add(aaa);
(I believe I have the syntax right)
If you already have the aaa method defined as a regular method, you'll be able to do something like:
list.add(MyClass::aaa);

You need to use reflection to get the Method, e.g.
this.getClass().getMethod("aaa")
Alternatively, if you don't need to access methods defined on a class, you can use Callables.
ArrayList<Callable> list = new ArrayList<Callable>();
list.add(new Callable() {
public String call() {
return "asdf";
}
});

I believe you can do it, but you need to use reflection to get the methods from a class/object. Maybe this links helps: http://tutorials.jenkov.com/java-reflection/methods.html
The way you have done it does not work.

You can call following method of Class
public Method[] getMethods() throws SecurityException
Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
public Method[] getDeclaredMethods() throws SecurityException
Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private methods, but excludes inherited methods.
Read more here
Cheers !!

Related

What do curly braces after a 'new' statement do?

I was looking at this example and was wondering what the first line does:
private SiteStreamsListener listener = new SiteStreamsListener() {
It looks like you can declare additional methods or override methods in this manner. Could I, for example, do the following?
ArrayList myList = new ArrayList() {
#Override String toString()
{
<my code here>
}
<insert new methods here>
}
These curly braces define an anonymous inner class.
This allows you to be able to override public and protected methods of the class you are initiating. You can do this with any non-final class, but is most useful with abstract classes and interfaces, which can only be initiated this way.
(To qualify that last sentence, interfaces with only one non-default method can be initiated using lambda statements in Java 8, circumventing this design method.)
ArrayList myList = new ArrayList() {
#Override
String toString()
{
//<my code here>
}
//<insert new methods here>
}
Yes you could do that. You can defiantly override public,protected methods. Although you can add new methods but those will not be accessiable through myList instance of ArrayList class.
Please refer to the java documentation for more details.
https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#declaring-anonymous-classes

How access private methods from anonymous class?

Suppose I have class:
MyObject b = new MyObject(){
private void method(){}
}
Is it possible to get method() by reflection? For toString I can write:
MyObject.class.getMethod("toString");
But what about for new created private method?
You have to invoke Object#getClass() on b reference to get the anonymous class, where the method is declared. MyObject.class will give you Class<MyObject>, which is not possibly what you want.
And then use Class#getDeclaredMethod() to get the private method:
Method method = b.getClass().getDeclaredMethod("method");
method.setAccessible(true);
method.invoke()
You can use it with:
Method method = b.getClass().getDeclaredMethod("method");
Here b.getClass() will return the class that the compiler generated for you for the anonymous inner class.
I can't easily imagine a situation in which that's a good approach, however.
Note that if you use a local named class, you don't even need to use reflection to call the method:
public class Test {
public static void main(String[] args) {
class Foo {
private void doSomething() {
System.out.println("Yes!");
}
};
Foo foo = new Foo();
foo.doSomething();
}
}
If you could give us more context about why you want this, we could probably be of more help in finding the best solution.

Java vector<object> class method access

I am trying to use a vector to hold my classes. These classes inherit methods from another class and have their own methods as well. What I am having trouble with is using the vector with objects to call the methods from the class within the object. I thought it would be something like:
public static void vSort(Vector<Object> vector) {
vector[0].generate();
}
with generate being a custom method i created with the student class within the object.
A better example
public class Method {
protected String name;
public void method() {
// some code
}
}
public class Student extends Method {
protected String last;
public void setUp() {
// some code
}
}
public class Main {
public static void main(String[] args)
{
Vector<Object> vector = new Vector<Object>();
Student stu = new Student(); // pretend this generates something
vector.add(stu);
}
The problem i am running into is there are many classes like student that build on Method. If i cant use Object that is fine with me but i need to access the code within the Method class.
Java doesn't have operator overloads. So the syntax is:
vector.get(0).generate();
However, this won't work at all in your case, because you have a Vector<Object>, and an Object doesn't have a generate method.
[Tangential note: vector is de facto deprecated; you should probably use ArrayList instead.]
you should use vector.get(0) to retrieve your object.
Also note, that Object does not declare generate() - so you are going to need to cast or specify your object as the generic type.
When you have a Vector<Object>, all the retrieval methods return Object, so you can't call subclass methods unless you explicitly downcast. You should use Vector<YourClass> instead, so that the references you get out of the vector are of type YourClass and you don't have to downcast them.

How to get a list of methods of an object or class?

I need to find a list of the methods and public properties that are in an object dynamically. I will not have access to the class's definition. Is it possible to get a list of methods of an object given a reference to the object? If so, how?
You can get the class by calling getClass() on the reference. From there, you can call getMethods(), getDeclaredMethods() etc. Sample code showing the methods in java.lang.String:
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
showMethods("hello");
}
private static void showMethods(Object target) {
Class<?> clazz = target.getClass();
for (Method method : clazz.getMethods()) {
System.out.println(method.getName());
}
}
}
Look at the docs for Class for more options of how to get methods etc.
java reflection api can do this for you.
http://download.oracle.com/javase/tutorial/reflect/class/classMembers.html
look here for a good introduction in java reflection:
http://tutorials.jenkov.com/java-reflection/index.html
With reflection you can get every method and object for a given class (next to many more features)

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