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 package org.openrdf.elmo.sesame.converters.impl;
30
31 import java.lang.reflect.Method;
32 import java.lang.reflect.Modifier;
33
34 import org.openrdf.elmo.exceptions.ElmoConversionException;
35 import org.openrdf.elmo.sesame.converters.Marshall;
36 import org.openrdf.model.Literal;
37 import org.openrdf.model.URI;
38 import org.openrdf.model.ValueFactory;
39
40 public class ValueOfMarshall<T> implements Marshall<T> {
41
42 private ValueFactory vf;
43
44 private Method valueOfMethod;
45
46 private URI datatype;
47
48 public ValueOfMarshall(ValueFactory vf, Class<T> type)
49 throws NoSuchMethodException {
50 this.vf = vf;
51 this.datatype = vf.createURI("java:", type.getName());
52 try {
53 this.valueOfMethod = type.getDeclaredMethod("valueOf", new Class[] { String.class });
54 if (!Modifier.isStatic(valueOfMethod.getModifiers()))
55 throw new NoSuchMethodException("valueOf Method is not static");
56 if (!type.equals(valueOfMethod.getReturnType()))
57 throw new NoSuchMethodException("Invalid return type");
58 } catch (NoSuchMethodException e) {
59 try {
60 this.valueOfMethod = type.getDeclaredMethod("getInstance", new Class[] { String.class });
61 if (!Modifier.isStatic(valueOfMethod.getModifiers()))
62 throw new NoSuchMethodException("getInstance Method is not static");
63 if (!type.equals(valueOfMethod.getReturnType()))
64 throw new NoSuchMethodException("Invalid return type");
65 } catch (NoSuchMethodException e2) {
66 throw e;
67 }
68 }
69 }
70
71 @SuppressWarnings("unchecked")
72 public Class<? extends T> getJavaClass() {
73 return (Class<? extends T>) valueOfMethod.getDeclaringClass();
74 }
75
76 public URI getDatatype() {
77 return datatype;
78 }
79
80 public void setDatatype(URI datatype) {
81 this.datatype = datatype;
82 }
83
84 @SuppressWarnings("unchecked")
85 public T deserialize(Literal literal) {
86 try {
87 return (T) valueOfMethod.invoke(null, new Object[] { literal.getLabel() });
88 } catch (Exception e) {
89 throw new ElmoConversionException(e);
90 }
91 }
92
93 public Literal serialize(T object) {
94 return vf.createLiteral(object.toString(), datatype);
95 }
96
97 }