|
| 1 | +package org.scijava.optional.examples.simple; |
| 2 | + |
| 3 | +import java.util.function.BiConsumer; |
| 4 | +import org.scijava.optional.AbstractOptions; |
| 5 | + |
| 6 | +public class Demo |
| 7 | +{ |
| 8 | + public static void main( String... args ) |
| 9 | + { |
| 10 | + print( "new MyOptions()", new MyOptions() ); |
| 11 | + print( "new MyOptions().number( 42 )", new MyOptions().number( 42 ) ); |
| 12 | + print( "new MyOptions().text( \"Hello\" )", new MyOptions().text( "Hello" ) ); |
| 13 | + print( "new MyOptions().text( \"World\" ).number( 12 )", new MyOptions().text( "World" ).number( 12 ) ); |
| 14 | + } |
| 15 | + |
| 16 | + private static void print( String title, MyOptions options ) |
| 17 | + { |
| 18 | + System.out.println( title ); |
| 19 | + System.out.println( " options = " + options ); |
| 20 | + System.out.println( " options.values = " + options.values ); |
| 21 | + System.out.println( " options.values.number() = " + options.values.number() ); |
| 22 | + System.out.println( " options.values.text() = " + options.values.text() ); |
| 23 | + System.out.println(); |
| 24 | + } |
| 25 | + |
| 26 | + public static class MyOptions extends AbstractOptions< MyOptions > |
| 27 | + { |
| 28 | + public MyOptions number( int number ) |
| 29 | + { |
| 30 | + return setValue( "number", number ); |
| 31 | + } |
| 32 | + |
| 33 | + public MyOptions text( String text ) |
| 34 | + { |
| 35 | + return setValue( "text", text ); |
| 36 | + } |
| 37 | + |
| 38 | + public Values values = new Values(); |
| 39 | + |
| 40 | + public class Values extends AbstractValues |
| 41 | + { |
| 42 | + public int number() |
| 43 | + { |
| 44 | + return getValueOrDefault( "number", -1 ); |
| 45 | + } |
| 46 | + |
| 47 | + public String text() |
| 48 | + { |
| 49 | + return getValueOrDefault( "text", "" ); |
| 50 | + } |
| 51 | + |
| 52 | + /* |
| 53 | + * Overriding forEach() makes default values show up in Values.toString(). |
| 54 | + * (Try commenting it out.) |
| 55 | + */ |
| 56 | + @Override |
| 57 | + public void forEach( final BiConsumer< String, Object > action ) |
| 58 | + { |
| 59 | + action.accept( "number", number() ); |
| 60 | + action.accept( "text", text() ); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments