Java, macro code, function address
I am beginner with Java, and I would like to write some code like this :
TEST(myfunction(1, 2, 3));
Where TEST is :
- Either a macro as used in C
- Either a function which need the address of the function myfunction
In my code, I would like TEST to do some code :
TEST(function) {
if (function())
// code
else
//code
}
I know pointers are not usable in Java. An idea to help me ?
[EDIT] Here is another example :
TEST(myfunction(1, 2, 3));
Where T开发者_运维技巧EST is implemented :
void TEST (function(args[])) {
try {
function();
}
catch (Exception e) {
// Exception happened !
}
}
Thanks to that, with only one code line, I will be able to use try catch !
Java doesn't have pointers to functions. The typical way functions are passed around in Java is to pass an object that implements Runnable
.
EDIT: I've revised my example to be closer to your second case.
In your case, where you want a boolean return value, you can define your own interface:
public interface BooleanTest {
boolean test(Object... args) throws Exception;
}
and then later:
class MyTest implements BooleanTest {
private boolean result;
public MyTest(int a, int b, int c) {
result = a + b == c;
}
// stupid test -- don't _have_ to declare "throws Exception"
public boolean test(Object... args) {
return result && args.length == 3;
}
}
TEST(new MyTest(1, 2, 3));
and inside TEST:
TEST(BooleanTest test) {
try {
if (test.test("Jack", "and", "Jill")) {
// ...
}
} catch (Exception e) {
}
}
You need to get an interface implementation as a parameter. Like this:
public static void testFunction(new FunctionContainer() {
@Override
public int function() {
...
}
};);
You can't really do this in java as methods are not Objects. To achieve your desired functionality you would need to wrap your function/method inside another object.
// Define a function interface that your test method takes as an argument.
public interface Function {
public abstract void doFunction();
}
// Test code
public void test(Function function) {
function.doFunction();
}
// You can then pass an implementation of Function to your test method
test(new Function() {
public void doFunction() {
// Function implementation
}
});
精彩评论