Java Object with optional fields - java

I have one scenario , please have a look
Sentence can be :
String Subject + String Verb + String Object
String Subject + String Verb + String Adverb+ String Object
String Subject + String Verb + String Adjective+ String Object
String Subject + String Verb
I want to create a Sentence class object.
Sentence s = new Sentence();
s.setSubject();
...
Now , I can keep all fields in Sentence class, but I want to ensure that no field must be null.
I want to create any type of sentence from fields that I initialize where i create object.
eg:
Sentence s = new Sentence();
s.setSubject();
s.setVerb();
s.setObject();
s.getValue(); // will return sentence value as S+V+O as I have set SVO
Sentence s = new Sentence();
s.setSubject();
s.setVerb();
s.getValue(); // will return sentence value as S+V as I have set SV
and so on ... can I do something like this in java.
Basically, I want to avoid uninitialized fields and nullpointers.
EDIT
Please note that if i leave fields empty ie "" or null , sentences formed will be like
"I am null to school." or (verb is null) .
"I am to school" (verb is empty) .
So, please consider this scenario before answering.

I will prefer using a builder pattern, make the usage clearer for the end user and avoid mistakes
Public class Sentence {
private String subject;
private String verb;
private String adjective;
private String object;
//package private to ensure no one can call it outside package, canbe made pvt as well
Sentence(String subject, String verb, String adjective, String object) {
this.subject = subject;
this.verb = verb;
this.adjective = adjective;
this.object = object;
}
public static class SentenceBuilder{
private String subject;
private String verb;
private String adjective;
private String object;
private static final String EMPTY = "";
private String sanitizeInput(String input){
if (input==null){
return EMPTY;
}
return input;
}
private String validateInput(String input){
if(input==null || input.isEmpty()){
throw new IllegalArgumentException("cant be null or empty");
}
return input;
}
public SentenceBuilder(String subject, String verb) {
this.subject = validateInput(subject);
this.verb = validateInput(verb);
}
public SentenceBuilder adjective(String adjective){
this.adjective = sanitizeInput(adjective);
return this;
}
public SentenceBuilder object(String object){
this.object = sanitizeInput(object);
return this;
}
public Sentence build(){
return new Sentence(subject,verb,adjective,object);
}
}
public static void main(String[] args) {
//sample usage
Sentence sentence = new SentenceBuilder("subject","verb")
.adjective("adjective")
.object("object")
.build();
}
}

Based on your comment, you don't want malformed sentences. That is, a sentence without a subject and a verb.
So, you can modify your constructor to get subject and verb and throw IllegalArgumentException if either of them is null or empty.
public Sentence(String subject, String verb) {
if (subject == null || subject.isEmpty()) {
throw new IllegalArgumentException("No Subject?");
}
// Same as above for verb.
this.subject = subject;
this.verb = verb;
}
This way, an object cannot be created without a subject or a verb.

In Java, there is no convenient way can do this, You need it's Option, use getOrElse to get the default value.In Scala, it has Option class do this thing.
I think you can use HashMap in Java to do this thing.
public class Test {
HashMap<String, String> data = new HashMap<>();
public void setSubject(String subject) {
data.put("subject", subject);
}
public void getSubject() {
data.getOrDefault("subject", "your_default_value");
}
public void setVerb(String verb) {
data.put("verb", verb);
}
public void getVerb() {
data.getOrDefault("verb", "your_default_value");
}
public void setObject(String object) {
data.put("object", object);
}
public void getObject() {
data.getOrDefault("object", "your_default_value");
}
}

First check whether the fields are null, and create a sentence based on that information:
if (s.getSubject != null)
{
//do something
}
if (s.getVerb != null)
{
//do something
}
etc.

Related

How to check null for all properties from an object with lambda expression [duplicate]

This would mean that the class was initialized, but the variables were not set.
A sample Class:
public class User {
String id = null;
String name = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The actual class is huge that I prefer not to check if(xyz == null) for each of the variables.
Another non-reflective solution for Java 8, in the line of paxdiabo's answer but without using a series of if's, would be to stream all fields and check for nullness:
return Stream.of(id, name)
.allMatch(Objects::isNull);
This remains quite easy to maintain while avoiding the reflection hammer.
Try something like this:
public boolean checkNull() throws IllegalAccessException {
for (Field f : getClass().getDeclaredFields())
if (f.get(this) != null)
return false;
return true;
}
Although it would probably be better to check each variable if at all feasible.
This can be done fairly easily using a Lombok generated equals and a static EMPTY object:
import lombok.Data;
public class EmptyCheck {
public static void main(String[] args) {
User user1 = new User();
User user2 = new User();
user2.setName("name");
System.out.println(user1.isEmpty()); // prints true
System.out.println(user2.isEmpty()); // prints false
}
#Data
public static class User {
private static final User EMPTY = new User();
private String id;
private String name;
private int age;
public boolean isEmpty() {
return this.equals(EMPTY);
}
}
}
Prerequisites:
Default constructor should not be implemented with custom behavior as that is used to create the EMPTY object
All fields of the class should have an implemented equals (built-in Java types are usually not a problem, in case of custom types you can use Lombok)
Advantages:
No reflection involved
As new fields added to the class, this does not require any maintenance as due to Lombok they will be automatically checked in the equals implementation
Unlike some other answers this works not just for null checks but also for primitive types which have a non-null default value (e.g. if field is int it checks for 0, in case of boolean for false, etc.)
If you want this for unit testing I just use the hasNoNullFieldsOrProperties() method from assertj
assertThat(myObj).hasNoNullFieldsOrProperties();
How about streams?
public boolean checkFieldsIsNull(Object instance, List<String> fieldNames) {
return fieldNames.stream().allMatch(field -> {
try {
return Objects.isNull(instance.getClass().getDeclaredField(field).get(instance));
} catch (IllegalAccessException | NoSuchFieldException e) {
return true;//You can throw RuntimeException if need.
}
});
}
"Best" is such a subjective term :-)
I would just use the method of checking each individual variable. If your class already has a lot of these, the increase in size is not going to be that much if you do something like:
public Boolean anyUnset() {
if ( id == null) return true;
if (name == null) return true;
return false;
}
Provided you keep everything in the same order, code changes (and automated checking with a script if you're paranoid) will be relatively painless.
Alternatively (assuming they're all strings), you could basically put these values into a map of some sort (eg, HashMap) and just keep a list of the key names for that list. That way, you could iterate through the list of keys, checking that the values are set correctly.
I think this is a solution that solves your problem easily: (return true if any of the parameters is not null)
public boolean isUserEmpty(){
boolean isEmpty;
isEmpty = isEmpty = Stream.of(id,
name)
.anyMatch(userParameter -> userParameter != null);
return isEmpty;}
Another solution to the same task is:(you can change it to if(isEmpty==0) checks if all the parameters are null.
public boolean isUserEmpty(){
long isEmpty;
isEmpty = Stream.of(id,
name)
.filter(userParameter -> userParameter != null).count();
return isEmpty > 0
}
The best way in my opinion is Reflection as others have recommended. Here's a sample that evaluates each local field for null. If it finds one that is not null, method will return false.
public class User {
String id = null;
String name = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isNull() {
Field fields[] = this.getClass().getDeclaredFields();
for (Field f : fields) {
try {
Object value = f.get(this);
if (value != null) {
return false;
}
}
catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}
public static void main(String args[]) {
System.out.println(new User().isNull());
}
}
Field[] field = model.getClass().getDeclaredFields();
for(int j=0 ; j<field.length ; j++){
String name = field[j].getName();
name = name.substring(0,1).toUpperCase()+name.substring(1);
String type = field[j].getGenericType().toString();
if(type.equals("class java.lang.String")){
Method m = model.getClass().getMethod("get"+name);
String value = (String) m.invoke(model);
if(value == null){
... something to do...
}
}
Best for me is
Stream.of(getClass().getDeclaredMethods()).allMatch(Objects::isNull);
It can be used in a custom annotation + annotation processor to automagically define a boolean isNull() method on the annotated classes.
Based on Irkwz's answer, but a different approach:
public class SomeClass{
private String field1;
private String field2;
private ComplexField field3;
private String field4;
private Integer field15;
public boolean isNullAllFields() {
return Stream.of(this.getClass().getDeclaredFields()).anyMatch(element -> (element != null));
}
}
And the end of the day u invoke isNullAllFields method to figure out wheter the object fields are empty.
If you want to do the opposite i.e check if some/all members of class are non-non, the check this answer.
In order to make sure that certain members of the class are always non-null, we can use lombok #NonNull annotation on the individual fields of the class.
import lombok.Data;
import lombok.NonNull;
#Data
public class DataClass {
#NonNull
private String data1;
private int data2;
#NonNull
private String data3;
#NonNull
private String data4;
#NonNull
private String data5;
private String data6;
DataClass(String data1,...) {
// constructor
}
}
Easiest way is to convert the class to a map and get its keys and with stream check if any or all key's values are null or not, you can take input from user as well whether they want to check for specific set of keys only!
Below is the code to check whether any of the key's value has null, you can change stream config to all match or any match as per your requirement
Just replace isNullOrEmpty method i have used with proper null or empty check condition for that particular collection
public boolean checkIfAnyFieldIsNull(Object instance, Set<String> fields){
try {
Map<String, Object> instanceMap = new Gson().fromJson(new GsonBuilder().serializeNulls().create().toJson(instance), Map.class);
if(!isNullorEmpty(instanceMap)) {
fields = isNullorEmpty(fields) ? instanceMap.keySet() : fields;
return fields.stream().anyMatch(curField -> isNull(instanceMap.get(curField)));
}else{
return false;
}
}catch (Exception e){
return false;
}
}
}
Try this method once, its works for me!!
private fun checkIfAnyDataIsNull(model: YourModelCass): Boolean {
return Stream.of<Any>(
model.date,
model.merchantName,
model.payment,
).allMatch(Objects::isNull)
}
You can use the simple solution:
if(user.equals(new User()){
//your processing goes here
}

What if an object's fields is an object...is there a way to get the latter object's fields?

I'm writing a program wherein I need to check an object's field values. For example, I have a class called Book which has String bookName, String publisher, and Author author. In Author, it has fields such as String firstName, String lastName, String dateOfBirth. I want to get the author's last name and change it to a new last name by looking through the fields of the Book. Also, I have to implement my method in a way wherein any kind of object can be used so method can also be used when changing first name of just the author.
I have used getDeclaredFields() to loop through the fields of my Book object, and am trying to find if one of the fields is its own object.
I have used "instanceof" Author but I need to find a way that doesn't need my hardcoding of the class name "Author"
public ArrayList<String> makeChanges(Object book){
ArrayList<String> changeList= new ArrayList<String>;
try{
Field[] bookFields = book.getClass().getDeclaredFields();
String changes = "";
for (Field field: bookFields){
field.setAccessible(true);
if (field.getName().equals("firstName")){
if (!(field.get(book).equals("Twilight"))){
changes = field.getName() + changed to "Twilight";
changeList.add(changes);
}
if (field.get(book) instanceof Author){
List<String> authorChanges = makeChanges(field.get(book));
changes = Arrays.toString(authorChanges.toArray()).replace("[","").replace("]","");
changeList.add(changes);
}
}
catch(Exception e){
System.out.println(e.toString());
}
return changeList;
}
Actual result: [bookName changed to "Twilight", author changed to "demo.Address#16f65612"]
Expected result should be: [bookName changed to "Twilight", firstName changed to "Eli"]
You need to check whether the object is primitive data type and wrapper classes. You can check the object using recursive function. Please find below the implementation classes that might suit your needs.
import java.lang.reflect.Field;
import java.util.ArrayList;
public class BookAuthor {
public static void main(String[] args) {
Book book = new Book();
book.bookName = "Twiligh";
book.publisher = "Oreilly";
book.author = new Author();
book.author.firstName = "";
book.author.lastName = "Elo";
ArrayList<String> changeList = new ArrayList<String>();
System.out.println(makeChanges(book,changeList));
}
public static ArrayList<String> makeChanges(Object book,ArrayList<String> changeList) {
try {
Field[] bookFields = book.getClass().getDeclaredFields();
Object object;
for (Field field : bookFields) {
field.setAccessible(true);
object = field.get(book);
if(object!=null && isWrapperAndPrimitiveType(object.getClass())) {
if(field.getName().equals("bookName")) {
if(!object.equals("Twilight")) {
field.set(book, "Twilight");
changeList.add(field.getName()+" changed to Twilight");
}
}
if(field.getName().equals("lastName")) {
if(!object.equals("Eli")) {
field.set(book, "Eli");
changeList.add(field.getName()+" changed to Eli");
}
}
}
if(object!=null && !isWrapperAndPrimitiveType(object.getClass())) {
makeChanges(object,changeList);
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
return changeList;
}
public static boolean isWrapperAndPrimitiveType(Class<?> clazz) {
return clazz.equals(Boolean.class) ||
clazz.equals(Integer.class) ||
clazz.equals(Character.class) ||
clazz.equals(Byte.class) ||
clazz.equals(Short.class) ||
clazz.equals(Double.class) ||
clazz.equals(Long.class) ||
clazz.equals(Float.class)||
clazz.equals(String.class) ||
clazz.equals(boolean.class) ||
clazz.equals(int.class) ||
clazz.equals(char.class) ||
clazz.equals(byte.class) ||
clazz.equals(short.class) ||
clazz.equals(double.class) ||
clazz.equals(long.class) ||
clazz.equals(float.class) ;
}
}
Book class
public class Book {
String bookName;
String publisher;
Author author;
}
Author class
public class Author {
String firstName;
String lastName;
String dateOfBirth;
}

How do I simplify such duplicated code in if else statement? [duplicate]

This question already has answers here:
Converting many 'if else' statements to a cleaner approach [duplicate]
(7 answers)
Closed 4 years ago.
I think this is a very common situation in web projects. Assume there is an entity such as:
//JAVA code
#Data
class Entity{
private String a;
private String aExt;
private String b;
private String bExt;
private String c;
private String cExt;
... something more ...
}
For some purpose, I need to get part of values from Entity according to a passed argument, like:
public ViewObject foo(Entity entity, String condition){
ViewObject vo = new ViewObject();
if("aRelated".equals(condition)){
vo.setValue1(entity.getA());
vo.setValue2(entity.getAExt());
}
else if("bRelated".equals(condition)){
vo.setValue1(entity.getB());
vo.setValue2(entity.getBExt());
}
else if(cRelated".equals(condition)){
vo.setValue1(entity.getC());
vo.setValue2(entity.getCExt());
}
... else statement if there are other values ....
return vo;
}
I know I can use switch-case statement to reduce some words in foo(), but there is no essential difference compared with if-else, especially when the Entity has many variables.
As a plain Example, foo() is only a view object builder, but my project is more complex which have many duplicated code with only different variable's name in each if-else statement.
How do I reduce the above duplicated code?
You can try creating two hash maps:
// name these properly!
HashMap<String, Function<Entity, String>> valueMap = new HashMap<>();
HashMap<String, Function<Entity, String>> extMap = new HashMap<>();
Add these KVPs:
// valueMap
"aRelated" - Entity::getA
"bRelated" - Entity::getB
"cRelated" - Entity::getC
// extMap
"aRelated" - Entity::getAExt
"bRelated" - Entity::getBExt
"cRelated" - Entity::getCExt
Now, you can do this without an if statement:
vo.setValue1(valueMap.get(condition).apply(entity));
vo.setValue2(extMap.get(condition).apply(entity));
Another option would be to use reflection:
import java.lang.reflect.Method;
import java.lang.reflext.InvocationTargetException;
...
public ViewObject foo(Entity e, String c) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
String[] methodNames = { "get" + c.substring(0,1).toUpperCase(), "get" + c.substring(0,1).toUpperCase() + "Ext" };
Method[] methods = { e.getClass().getDeclaredMethod(methodNames[0]), e.getClass().getDeclaredMethod(methodNames[1]) };
ViewObject vo = new ViewObject();
vo.setValue1((String)methods[0].invoke(e));
vo.setValue2((String)methods[1].invoke(e));
return vo;
}
Although I have to admit I personally like the map approach of the other answers more, just showing more options.
Use of a Map would do the trick:
class EntityPart {
String s;
String sExt;
}
class Entity {
Map<String,EntityPart> m = new HashMap<>();
m.add("aRelated",new EntityPart());
m.add("bRelated",new EntityPart());
....
}
public ViewObject foo(Entity entity, String condition) {
ViewObject vo = new ViewObject();
EntityPart ep = entity.m.get(condition);
vo.setValue1(ep.s);
vo.setValue2(ep.sExt);
return vo;
}
Make Entity as enum instead of class.
public enum Entity {
A("a", "aExt"), B("b", "bExt"), C("c", "cExt");
private final String name;
private final String text;
private Entity(String name, String text) {
this.name = name;
this.text = text;
}
public String getName() {
return name;
}
public String getText() {
return text;
}
public static Entity fromString(String raw) {
return LOOKUP.get(raw);
}
private static final Map<String, Entity> LOOKUP = new HashMap<>();
static {
for (Entity e : values()) {
LOOKUP.put(e.getName(), e);
}
}
}
And modify your foo method as
public ViewObject foo(String condition){
/*
* pass condition as "a", "b", "c" only not "aRelated", "bRelated", "cRelated"
*
*/
ViewObject vo = new ViewObject();
Entity e = Entity.fromString(condition);
if(null != e) {
vo.setValue1(e.getName());
vo.setValue2(e.getText());
}
return vo;
}

Determining Class from String representation of an Object

Consider I am given an array of Classes and string representation of an Object. How can I get which Class this Object belongs to?
I thought of this approach but I don't know how to achieve it:
Iterating over Class array and then getting all instances of that
class.Then convert each instance to its String representation and then
check if it equals given String.
The problem I'm having is how do I get all Instances of that Class?
We can use getInstance() if all are Singleton class but what if not?
Please clarify my if I have any misunderstanding.
import java.util.*;
public class Class_instance {
public static void main(String args[]){
List<Class> class_list = new ArrayList<Class>();
Test_class x = new Test_class();
Test y = new Test();
class_list.add(x.getClass());
class_list.add(y.getClass());
String ex = x.toString();
}
}
How to know what class ex represents here?
Short answer - no, this won't work.
The toString() method returns a textual representation of the object, but there is no guarantee this will include the class name. For example, for Strings, toString() returns the value of the string. In particular any textual representation could come from a string.
If you have a specific list of classes you want to look for (and they have identifiable values), you could write regexes which would identify their toString values.
Using the Class object directly is more likely to be what you're after here:
public static void main(String [] args){
Class[] possibleClasses= {String.class, Integer.class};
System.out.println(identifyClass("string", possibleClasses));
System.out.println(identifyClass(4, possibleClasses));
}
#SuppressWarnings("raw")
public static Class identifyClass(Object o, Class[] possibleClasses){
// Ignore null inputs
if (o==null){
return null;
}
// Find the first entry which matches o
for (Class c : possibleClasses){
if (c.isInstance(o)){
return c;
}
}
// If no matches are found, return null.
return null;
}
Although that said, maybe this would be enough?
System.out.println(ex.getClass().getName());
As mentioned we need to know what string representation means.
In most application (AFAIK) instanceof should suffice to check if object belong to a certain class or not . Another way is to define a overwrite the toString method
public class House {
public String address;
public String type;
public House(String add){
this.address = add;
}
#Override
public String toString() {
return (address + "-" + type) ;
}
}
If given a String sample = "Hogwart-Castle"; You can use the following :
houseObj.toString().equals(sample);
If you own the classes you want to search, you can keep the track of their instances by creating a new class (I called it MyObject) with a static field that you fill when a new object of that class is created, and then extending the classes you want to keep track with this new class.
public class MyObject {
private static Map<Class<?>, List<WeakReference<?>>> instances = new HashMap<>();
public MyObject() {
if (!instances.containsKey(getClass())) {
instances.put(getClass(), new ArrayList<>());
}
instances.get(getClass()).add(new WeakReference<>(this));
}
public static List<Object> getInstances(List<Class<?>> classes) {
List<Object> result = new ArrayList<>();
for (Class<?> clazz : classes) {
if (instances.containsKey(clazz)) {
Iterator<WeakReference<?>> iterator = instances.get(clazz).iterator();
while (iterator.hasNext()) {
WeakReference<?> ref = iterator.next();
if (ref.get() == null) {
iterator.remove();
} else {
result.add(ref.get());
}
}
}
}
return result;
}
}
Then you can use it like this:
public class Main {
public static void main(String[] args) {
Dog d1 = new Dog("I'm a dog");
Dog d2 = new Dog("I'm an animal");
Cat c1 = new Cat("I'm an animal");
List<Class<?>> classList = new ArrayList<>();
classList.add(Dog.class);
find("I'm an animal", classList); // Found a Dog
classList.add(Cat.class);
find("I'm an animal", classList); // Found a Dog and a Cat
find("I'm a dog", classList); // Found a Dog
}
private static void find(String str, List<Class<?>> classes) {
for (Object o : MyObject.getInstances(classes)) {
if (o.toString().equals(str)) {
System.out.println("Found a " + o.getClass().getSimpleName());
}
}
}
}
My Dog class (and similarly the Cat class) looks like this:
public class Dog extends MyObject {
String description;
public Dog(String description) {
this.description = description;
}
#Override
public String toString() {
return description;
}
}
Beware that toString() doesn't return a unique representation of an object (as shown in my example), unless you have full control over the toString() of that objects and you ensure it yourself.

How do I format a string with properties from a bean

I want to create a String using a format, replacing some tokens in the format with properties from a bean. Is there a library that supports this or am I going to have to create my own implementation?
Let me demonstate with an example. Say I have a bean Person;
public class Person {
private String id;
private String name;
private String age;
//getters and setters
}
I want to be able to specify format strings something like;
"{name} is {age} years old."
"Person id {id} is called {name}."
and automatically populate the format placeholders with values from the bean, something like;
String format = "{name} is {age} old."
Person p = new Person(1, "Fred", "32 years");
String formatted = doFormat(format, person); //returns "Fred is 32 years old."
I've had a look at MessageFormat but this only seems to allow me to pass numeric indexes, not bean properties.
Rolled my own, testing now. Comments welcome.
import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BeanFormatter<E> {
private Matcher matcher;
private static final Pattern pattern = Pattern.compile("\\{(.+?)\\}");
public BeanFormatter(String formatString) {
this.matcher = pattern.matcher(formatString);
}
public String format(E bean) throws Exception {
StringBuffer buffer = new StringBuffer();
try {
matcher.reset();
while (matcher.find()) {
String token = matcher.group(1);
String value = getProperty(bean, token);
matcher.appendReplacement(buffer, value);
}
matcher.appendTail(buffer);
} catch (Exception ex) {
throw new Exception("Error formatting bean " + bean.getClass() + " with format " + matcher.pattern().toString(), ex);
}
return buffer.toString();
}
private String getProperty(E bean, String token) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field field = bean.getClass().getDeclaredField(token);
field.setAccessible(true);
return String.valueOf(field.get(bean));
}
public static void main(String[] args) throws Exception {
String format = "{name} is {age} old.";
Person p = new Person("Fred", "32 years", 1);
BeanFormatter<Person> bf = new BeanFormatter<Person>(format);
String s = bf.format(p);
System.out.println(s);
}
}
Yes, it's possible using the Pojomatic library. Implement and plug in your own implementation of PojoFormatter. Pojomator#doToString(T) may be also interesting.
Don't really know how complex is the model you're up to consume but if you want to deal with object trees I would implement my own formatter using Jexl as expession language this way:
Initialize a singleton Jexl engine
Populate a MapContext with all the objects you want to consume when formatting strings
Parse your strings and create a Jexl expression per "${}" construct you have.
Evaluate the previous created expressions against the object context map.
The good thing about Jexl is that it will allow you to use method calls, not just properties.
Hope it helps.
Not quite close, but you can look at StringTemplate, your bean:
public static class User {
public int id; // template can directly access via u.id
private String name; // template can't access this
public User(int id, String name) { this.id = id; this.name = name; }
public boolean isManager() { return true; } // u.manager
public boolean hasParkingSpot() { return true; } // u.parkingSpot
public String getName() { return name; } // u.name
public String toString() { return id+":"+name; } // u
}
Then you can render it like this:
ST st = new ST("<b>$u.id$</b>: $u.name$", '$', '$');
st.add("u", new User(999, "parrt"));
String result = st.render(); // "<b>999</b>: parrt"
Code sample above taken from ST4 Introduction

Categories