if you mean an anonymous function, and are using a version of Java before Java 8, then in a word, no. (Read about lambda expressions if you use Java 8+)
However, you can implement an interface with a function like so :
Comparator<String> c = new Comparator<String>() {
int compare(String s, String s2) { ... }
};
and you can use this with inner classes to get an almost-anonymous function :)
Answer from chris on Stack Overflowanonymous method java
java - Using methods on anonymous classes - Stack Overflow
java - Invoking a method of an anonymous class - Stack Overflow
[Java] can someone explain anonymous classes (and perhaps how it ties into lamda) in layman terms?
if you mean an anonymous function, and are using a version of Java before Java 8, then in a word, no. (Read about lambda expressions if you use Java 8+)
However, you can implement an interface with a function like so :
Comparator<String> c = new Comparator<String>() {
int compare(String s, String s2) { ... }
};
and you can use this with inner classes to get an almost-anonymous function :)
Here's an example of an anonymous inner class.
System.out.println(new Object() {
@Override public String toString() {
return "Hello world!";
}
}); // prints "Hello world!"
This is not very useful as it is, but it shows how to create an instance of an anonymous inner class that extends Object and @Override its toString() method.
See also
- JLS 15.9.5 Anonymous Class Declarations
Anonymous inner classes are very handy when you need to implement an interface which may not be highly reusable (and therefore not worth refactoring to its own named class). An instructive example is using a custom java.util.Comparator<T> for sorting.
Here's an example of how you can sort a String[] based on String.length().
import java.util.*;
//...
String[] arr = { "xxx", "cd", "ab", "z" };
Arrays.sort(arr, new Comparator<String>() {
@Override public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
});
System.out.println(Arrays.toString(arr));
// prints "[z, cd, ab, xxx]"
Note the comparison-by-subtraction trick used here. It should be said that this technique is broken in general: it's only applicable when you can guarantee that it will not overflow (such is the case with String lengths).
See also
- Java Integer: what is faster comparison or subtraction?
- Comparison-by-subtraction is broken in general
- Create a Sorted Hash in Java with a Custom Comparator
- How are Anonymous (inner) classes used in Java?
I kind of learnt about anonymous and functional methods, but I am confused here:
public abstract class A {
public void f1(String str) {
System.out.println(str);
}
public static void main(String[]args) {
A a = new A()
{
public void f2(String str) {
}
};
a.f2("abc");
}
}I have error in line
a.f2("abc")
lets say I want to use f2 method (the anonymous function) how could I use it outside of A? or is it possible only inside A ?
One acronym: KISS:
Yes, you could do all kinds of magic, calling methods via reflection, etc. But why bother?
Create a main method which takes the first argument and creates a CreateHandler or a VerificationHandler. Both implement the Handler interface which has this method:
void run(String[] args);
So after the switch, you can call the new handler with handler.run(args), no matter which one it is.
The handlers can then examine the command lines to find out what the user wants.
Move common code (like loading/saving) into helper classes. Keep methods short (5-15 lines). Each method should do one thing. Move complex tasks into helper methods.
If I understand your question/assignment properly (and I'm not sure that I do, what exactly are the requirements of the assignment? Are you required to use anonymous classes? There's really no such thing as an anonymous method in Java, only anonymous classes.), it sounds like you might want a one-off Vertification class, or a static method.
The one-off method:
Verification v = new Verification(commandLineArgs);
v.verify();
// Done with 'v'
The static method... method:
Verification.verify(commandLineArgs);
Where the method is defined in the class as:
public class Verification {
...
public static void verify(String ... commandLineArgs) {
}
...
}
Can somebody point me to the part of the specification that addresses this?
This will mostly be defined in the section concerning Method invocation expressions:
The first step in processing a method invocation at compile time is to figure out the name of the method to be invoked and which class or interface to search for definitions of methods of that name.
For the class or interface to search, there are six cases to consider, depending on the form that precedes the left parenthesis of the MethodInvocation:
- [...]
- If the form is
Primary . [TypeArguments] Identifier, then letTbe the type of the Primary expression. The class or interface to search isTifTis a class or interface type, or the upper bound ofTifTis a type variable.
Here, the Primary expression is the class instance creation expression. So the type to search is the anonymous type.
Am I right in thinking that the only way you can invoke hello is immediately like this. What about reflection?
As long as an expression evaluates to the anonymous type T, whether through direct access like you have, or through generics, you have access (regular access rules apply) to the members that T declares. This isn't limited to methods. You can access fields or types, though it's not as useful for types. For example,
Object var = new Object() {
class Nested {
}
}.new Nested();
Since there's no way to refer to the nested type without the enclosing type, you can't declare a variable of that nested type. The usefulness declines very quickly. (Presumably, that's also why you can't have a static nested type within this anonymous class.)
Reflection also exposes this method. The generated anonymous class contains this method, so you can retrieve it and invoke it. The process is the same. The fact that the instance is from an anonymous class doesn't matter. The same strategy as presented in How do I invoke a Java method when given the method name as a string? applies.
For example,
Object ref = new Object() {
public void method() {
System.out.println("hidden");
}
};
Class<?> anonymousClass = ref.getClass();
Method method = anonymousClass.getMethod("method");
method.invoke(ref, new Object[0]);
Don't ever write code like this.
As posted, there isn't a way to get the anonymous methods from the Object instance. And, it makes Anonymous classes look pointless. But, you could (and I usually would) use it to implement an interface. Something like,
static interface Hello {
void hello();
}
public static void main(String[] args) {
Hello o = new Hello() {
public void hello() {
System.out.println("Hello World!");
}
};
o.hello();
}
Or, more commonly, for call-backs with JFC/Swing and ActionListener.