Просмотр исходного кода

commit e125e9697d06b231efb478921a0299ef072b9791
Author: Hemanth Yamijala <yhemanth@yahoo-inc.com>
Date: Tue Feb 9 11:10:54 2010 +0530

HADOOP:6161 from http://issues.apache.org/jira/secure/attachment/12434928/hadoop-6161-yahoo-20-v1.patch

+++ b/YAHOO-CHANGES.txt
+ HADOOP-6161. Add get/setEnum methods to Configuration. (cdouglas)
+


git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.20-security-patches@1077195 13f79535-47bb-0310-9956-ffa450edef68

Owen O'Malley 14 лет назад
Родитель
Сommit
8d213d7ae2

+ 24 - 0
src/core/org/apache/hadoop/conf/Configuration.java

@@ -626,6 +626,30 @@ public class Configuration implements Iterable<Map.Entry<String,String>>,
     setIfUnset(name, Boolean.toString(value));
   }
 
+  /**
+   * Set the value of the <code>name</code> property to the given type. This
+   * is equivalent to <code>set(&lt;name&gt;, value.toString())</code>.
+   * @param name property name
+   * @param value new value
+   */
+  public <T extends Enum<T>> void setEnum(String name, T value) {
+    set(name, value.toString());
+  }
+
+  /**
+   * Return value matching this enumerated type.
+   * @param name Property name
+   * @param defaultValue Value returned if no mapping exists
+   * @throws IllegalArgumentException If mapping is illegal for the type
+   * provided
+   */
+  public <T extends Enum<T>> T getEnum(String name, T defaultValue) {
+    final String val = get(name);
+    return null == val
+      ? defaultValue
+      : Enum.valueOf(defaultValue.getDeclaringClass(), val);
+  }
+
   /**
    * A class that represents a set of positive integer ranges. It parses 
    * strings of the form: "2-3,5,7-" where ranges are separated by comma and 

+ 17 - 0
src/test/org/apache/hadoop/conf/TestConfiguration.java

@@ -351,6 +351,23 @@ public class TestConfiguration extends TestCase {
     assertEquals(-20, conf.getLong("test.int3", 0));
   }
 	
+  enum Dingo { FOO, BAR };
+  enum Yak { RAB, FOO };
+  public void testEnum() throws IOException {
+    Configuration conf = new Configuration();
+    conf.setEnum("test.enum", Dingo.FOO);
+    assertSame(Dingo.FOO, conf.getEnum("test.enum", Dingo.BAR));
+    assertSame(Yak.FOO, conf.getEnum("test.enum", Yak.RAB));
+    boolean fail = false;
+    try {
+      conf.setEnum("test.enum", Dingo.BAR);
+      Yak y = conf.getEnum("test.enum", Yak.FOO);
+    } catch (IllegalArgumentException e) {
+      fail = true;
+    }
+    assertTrue(fail);
+  }
+
   public void testReload() throws IOException {
     out=new BufferedWriter(new FileWriter(CONFIG));
     startConfig();