blob: d53af9c5c2e17692bd737dad1f7f86e0bea69dee [file] [log] [blame]
Jon Skeet8f8186a2009-01-16 10:57:40 +00001using System;
2using System.Collections.Generic;
3using System.Reflection;
4using System.Text;
5
6namespace Google.ProtocolBuffers {
7 /// <summary>
8 /// Utilities for arbitrary messages of an unknown type. This class does not use
9 /// generics precisely because it is designed for dynamically discovered types.
10 /// </summary>
11 public static class MessageUtil {
12
13 /// <summary>
14 /// Returns the default message for the given type. If an exception is thrown
15 /// (directly from this code), the message will be suitable to be displayed to a user.
16 /// </summary>
17 /// <param name="type"></param>
18 /// <exception cref="ArgumentNullException">The type parameter is null.</exception>
19 /// <exception cref="ArgumentException">The type doesn't implement IMessage, or doesn't
20 /// have a static DefaultMessage property of the same type, or is generic or abstract.</exception>
21 /// <returns></returns>
22 public static IMessage GetDefaultMessage(Type type) {
23 if (type == null) {
24 throw new ArgumentNullException("type", "No type specified.");
25 }
26 if (type.IsAbstract || type.IsGenericTypeDefinition) {
27 throw new ArgumentException("Unable to get a default message for an abstract or generic type (" + type.FullName + ")");
28 }
29 if (!typeof(IMessage).IsAssignableFrom(type)) {
30 throw new ArgumentException("Unable to get a default message for non-message type (" + type.FullName + ")");
31 }
32 PropertyInfo property = type.GetProperty("DefaultInstance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
33 if (property == null) {
34 throw new ArgumentException(type.FullName + " doesn't have a static DefaultInstance property");
35 }
36 if (property.PropertyType != type) {
37 throw new ArgumentException(type.FullName + ".DefaultInstance property is of the wrong type");
38 }
39 return (IMessage) property.GetValue(null, null);
40 }
41
42 /// <summary>
43 /// Returns the default message for the type with the given name. This is just
44 /// a convenience wrapper around calling Type.GetType and then GetDefaultMessage.
45 /// If an exception is thrown, the message will be suitable to be displayed to a user.
46 /// </summary>
47 /// <param name="typeName"></param>
48 /// <exception cref="ArgumentNullException">The typeName parameter is null.</exception>
49 /// <exception cref="ArgumentException">The type doesn't implement IMessage, or doesn't
50 /// have a static DefaultMessage property of the same type, or can't be found.</exception>
51 public static IMessage GetDefaultMessage(string typeName) {
52 if (typeName == null) {
53 throw new ArgumentNullException("typeName", "No type name specified.");
54 }
55 Type type = Type.GetType(typeName);
56 if (type == null) {
57 throw new ArgumentException("Unable to load type " + typeName);
58 }
59 return GetDefaultMessage(type);
60 }
61 }
62}