Bukkit-API  1.7.9-R0.2
The inofficial Bukkit-API
MetadataValueAdapter.java
1 package org.bukkit.metadata;
2 
3 import java.lang.ref.WeakReference;
4 
5 import org.apache.commons.lang.Validate;
6 import org.bukkit.plugin.Plugin;
8 
9 /**
10  * Optional base class for facilitating MetadataValue implementations.
11  * <p>
12  * This provides all the conversion functions for MetadataValue so that
13  * writing an implementation of MetadataValue is as simple as implementing
14  * value() and invalidate().
15  */
16 public abstract class MetadataValueAdapter implements MetadataValue {
17  protected final WeakReference<Plugin> owningPlugin;
18 
19  protected MetadataValueAdapter(Plugin owningPlugin) {
20  Validate.notNull(owningPlugin, "owningPlugin cannot be null");
21  this.owningPlugin = new WeakReference<Plugin>(owningPlugin);
22  }
23 
25  return owningPlugin.get();
26  }
27 
28  public int asInt() {
29  return NumberConversions.toInt(value());
30  }
31 
32  public float asFloat() {
33  return NumberConversions.toFloat(value());
34  }
35 
36  public double asDouble() {
37  return NumberConversions.toDouble(value());
38  }
39 
40  public long asLong() {
41  return NumberConversions.toLong(value());
42  }
43 
44  public short asShort() {
45  return NumberConversions.toShort(value());
46  }
47 
48  public byte asByte() {
49  return NumberConversions.toByte(value());
50  }
51 
52  public boolean asBoolean() {
53  Object value = value();
54  if (value instanceof Boolean) {
55  return (Boolean) value;
56  }
57 
58  if (value instanceof Number) {
59  return ((Number) value).intValue() != 0;
60  }
61 
62  if (value instanceof String) {
63  return Boolean.parseBoolean((String) value);
64  }
65 
66  return value != null;
67  }
68 
69  public String asString() {
70  Object value = value();
71 
72  if (value == null) {
73  return "";
74  }
75  return value.toString();
76  }
77 
78 }