View Javadoc
1   /*
2    * Copyright (C) 2013 4th Line GmbH, Switzerland
3    *
4    * The contents of this file are subject to the terms of either the GNU
5    * Lesser General Public License Version 2 or later ("LGPL") or the
6    * Common Development and Distribution License Version 1 or later
7    * ("CDDL") (collectively, the "License"). You may not use this file
8    * except in compliance with the License. See LICENSE.txt for more
9    * information.
10   *
11   * This program is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14   */
15  
16  package org.fourthline.cling.model.types;
17  
18  import java.lang.reflect.ParameterizedType;
19  
20  /**
21   * @author Christian Bauer
22   */
23  public abstract class AbstractDatatype<V> implements Datatype<V> {
24  
25      private Builtin builtin;
26  
27      protected Class<V> getValueType() {
28          return (Class<V>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
29      }
30  
31      @Override
32      public boolean isHandlingJavaType(Class type) {
33          return getValueType().isAssignableFrom(type);
34      }
35  
36      @Override
37      public V valueOf(String s) throws InvalidValueException {
38          return null;
39      }
40  
41      public Builtin getBuiltin() {
42          return builtin;
43      }
44  
45      public void setBuiltin(Builtin builtin) {
46          this.builtin = builtin;
47      }
48  
49      public String getString(V value) throws InvalidValueException {
50          if (value == null) return "";
51          if (!isValid(value)) {
52              throw new InvalidValueException("Value is not valid: " + value);
53          }
54          return value.toString();
55      }
56  
57      public boolean isValid(V value) {
58          return value == null || getValueType().isAssignableFrom(value.getClass());
59      }
60  
61      @Override
62      public String toString() {
63          return "(" + getClass().getSimpleName() + ")";
64      }
65  
66      public String getDisplayString() {
67          if (this instanceof CustomDatatype) {
68              return ((CustomDatatype)this).getName();
69          } else if (getBuiltin() != null) {
70              return getBuiltin().getDescriptorName();
71          } else {
72              return getValueType().getSimpleName();
73          }
74      }
75  
76  }