-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicExample.xtend
More file actions
59 lines (51 loc) · 1.73 KB
/
BasicExample.xtend
File metadata and controls
59 lines (51 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package blang.inits
import blang.inits.Arg
import blang.inits.parsing.Posix
/**
* Walking through some simple usage examples.
*
* Note that this is shown in Xtend, but usage in Java is virtually identical.
*/
class BasicExample {
/**
* Let's say we are interested in creating command line arguments
* for the following class:
*/
static class MyClass {
/**
* All we need to do is:
*
* (1) add the "@Arg" annotation to all parameters we want to parse
* (the name of the command line is just the field name here).
*/
@Arg
public int anInteger
/**
* (2) Make sure there is a zero-arg constructor available
* (more complex options also available).
*/
new() {}
}
/**
* That's it! We can now create an instance as follows:
*/
def static void main(String [] args) {
val Creator creator = Creators.conventional()
val instance = creator.init(
MyClass, // Note: would be "MyClass.class" in Java
Posix.parse("--anInteger", "123") // or "Posix.parse(args)" to read from the command line
)
println(instance.anInteger) // 123
// You can also show a usage string for the last call of init(..) using:
println(creator.usage)
// --anInteger <Integer>
// If there are errors, the call to init(..) returns an exception;
// but use the following to get a more comprehensive diagnostic:
try {
creator.init(MyClass, Posix.parse("--anInteger", "abc"))
} catch (Exception e) { }
println("number of errors: " + creator.errors.size()) // 1, intentionally
println(creator.errorReport)
// --anInteger: Failed to build type <class java.lang.Integer>, possibly a parsing error (input: abc)
}
}