1 package net.sourceforge.jparam.output;
2
3 import java.io.PrintStream;
4 import java.lang.reflect.Method;
5 import java.lang.reflect.Modifier;
6
7 import net.sourceforge.jparam.JParamException;
8 import net.sourceforge.jparam.util.Utils;
9
10 public class SerializeMethodSerializer implements ISerializer {
11 Method m;
12 Class supportedClass;
13
14 public SerializeMethodSerializer(Method m) {
15 this.m = m;
16 String validationError = getMethodValidError(m);
17 Utils.assert(validationError == null, validationError);
18
19 supportedClass = m.getParameterTypes()[0];
20 }
21
22
23
24
25 public Class getSupportedClass() {
26 return supportedClass;
27 }
28
29 public static String getMethodValidError(Method m) {
30 if (!m.getName().equals("serialize"))
31 return "Serialize method name must be \"serialize\", method: " + m;
32 if (!m.getReturnType().equals(void.class))
33 return "Serialize method must not have a return value, method: "
34 + m;
35 if ((m.getParameterTypes().length != 2)
36 || (!m.getParameterTypes()[1]
37 .isAssignableFrom(PrintStream.class)))
38 return "Serialize method must have two parameters, the second should be a PrintStream, method: "
39 + m;
40 if (!Modifier.isStatic(m.getModifiers()))
41 return "Serialize method must be static, method: " + m;
42 return null;
43 }
44
45 public static boolean isMethodValid(Method m) {
46 return getMethodValidError(m) == null;
47 }
48
49 public void serialize(Object obj, PrintStream out) throws JParamException {
50 try {
51 m.invoke(null, new Object[] { obj, out });
52 } catch (Exception e) {
53 throw new JParamException("Error serializing object: " + obj
54 + " using serializer: " + this, e);
55 }
56 }
57
58 public String toString() {
59 return "Serialize method serializer for type: "
60 + getSupportedClass().getName() + " using method: " + m;
61 }
62 }