If you want to load objects from the content it is necessary to create a custom TypeLoader.
For example, if we have the following resource file:
testfuse2.resources
TestFuse2.person=Jon,Doe
and a Person POJO defined as follows:
Person.java
public class Person
{
private String firstName;
private String lastName;
public Person(String firstName,String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String toString()
{
return this.getClass().getName()+"[firstName="+firstName+", lastName="+lastName+"]";
}
}
Then we need to create our own typeloader to parse the Strign Jon,Doe to return a Person object.
Our TypeLoader looks like this:
PersonLoader.java
import java.util.Map;
import org.jdesktop.fuse.TypeLoader;
public class PersonLoader extends TypeLoader<Person>
{
@SuppressWarnings("unchecked")
public PersonLoader()
{
super(Person.class);
}
@Override
public Person loadType(String name, String value, Class resolver, Mapmap)
{
String[] parts = value.split(",");
return new Person(parts[0],parts[1]);
}
}
Now all we need to do, is modify our original code from my last post to register the new typeloader.
TestFuse2.java
import org.jdesktop.fuse.InjectedResource;
import org.jdesktop.fuse.ResourceInjector;
import org.jdesktop.fuse.TypeLoaderFactory;
public class TestFuse2
{
@InjectedResource
private Person person;
public String toString()
{
return person.toString();
}
public static void main(String[] args)
{
ResourceInjector.get().load(TestFuse2.class.getResource("testfuse2.resources"));
TypeLoaderFactory.addTypeLoader(new PersonLoader());
TestFuse2 testFuse2 = new TestFuse2();
ResourceInjector.get().inject(testFuse2);
System.out.println(testFuse2);
}
}
No comments:
Post a Comment