This example Groovy source code file (GString.java) is included in the DevDaily.com
"Java Source Code
Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.
/*
* Copyright 2003-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovy.lang;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.codehaus.groovy.runtime.InvokerHelper;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
/**
* Represents a String which contains embedded values such as "hello there
* ${user} how are you?" which can be evaluated lazily. Advanced users can
* iterate over the text and values to perform special processing, such as for
* performing SQL operations, the values can be substituted for ? and the
* actual value objects can be bound to a JDBC statement. The lovely name of
* this class was suggested by Jules Gosnell and was such a good idea, I
* couldn't resist :)
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan
* @version $Revision: 21240 $
*/
public abstract class GString extends GroovyObjectSupport implements Comparable, CharSequence, Writable, Buildable, Serializable {
static final long serialVersionUID = -2638020355892246323L;
/**
* A GString containing a single empty String and no values.
*/
public static final GString EMPTY = new GString(new Object[0]) {
public String[] getStrings() {
return new String[]{""};
}
};
private Object[] values;
public GString(Object values) {
this.values = (Object[]) values;
}
public GString(Object[] values) {
this.values = values;
}
// will be static in an instance
public abstract String[] getStrings();
/**
* Overloaded to implement duck typing for Strings
* so that any method that can't be evaluated on this
* object will be forwarded to the toString() object instead.
*/
public Object invokeMethod(String name, Object args) {
try {
return super.invokeMethod(name, args);
}
catch (MissingMethodException e) {
// lets try invoke the method on the real String
return InvokerHelper.invokeMethod(toString(), name, args);
}
}
public Object[] getValues() {
return values;
}
public GString plus(GString that) {
List<String> stringList = new ArrayList();
List<Object> valueList = new ArrayList