Re: storing data with variable numbers and types
3rdshiftcoder wrote:
i have some data i want to store. in the code sample below, the key pieces
of data
i wish to store are the name of the function: like, parameter1: str1,
paramater2: str2.
I'm not entirely sure what you are after.
The Java language has no support for passing functions around like
objects. If you want to pass things around like objects, use objects.
Possibly what you might want is an interface for your 'functions', that
just has one method defined. You can then implement your function
interface using anonymous inner classes, that can also take a snapshot
of (final) local variables.
So for instance.
interface TestString {
boolean test(String str);
}
....
public static TestString startsWith(final String start) {
return new TestString() {
public boolean test(String str) {
return str.startsWith(start);
// ^^^^^ a final local variable
// from the enclosing method
}
};
}
....
TestString fileURLTest = startsWith("file:");
...
...
System.err.println(
fileURLTest.test("file:///etc/passwd")
);
The anonymous inner class in startsWith above is the equivalent of doing:
class StartsWithTestString implements TestString {
private final String start;
public StartsWithTestString(String start) {
this.start = start;
}
public boolean test(String str) {
return str.startsWith(start);
}
}
....
public static TestString startsWith(final String start) {
return new StartsWithTestString(start);
}
[Disclaimer: I've not compiled or tested this code.]
Tom Hawtin