Java/Reflection/Enum

Материал из Java эксперт
Перейти к: навигация, поиск

Deal with enum type and its method

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import static java.lang.System.out;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
enum Charge {
  POSITIVE, NEGATIVE, NEUTRAL;
  Charge() {
    out.format("under construction%n");
  }
}
public class EnumTrouble {
  public static void main(String... args) {
    try {
      Class<?> c = Charge.class;
      Constructor[] ctors = c.getDeclaredConstructors();
      for (Constructor ctor : ctors) {
        out.format("Constructor: %s%n", ctor.toGenericString());
        ctor.setAccessible(true);
        ctor.newInstance();
      }
      // production code should handle these exceptions more gracefully
    } catch (InstantiationException x) {
      x.printStackTrace();
    } catch (IllegalAccessException x) {
      x.printStackTrace();
    } catch (InvocationTargetException x) {
      x.printStackTrace();
    }
  }
}





Deal with enum type field

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.lang.reflect.Field;
enum E0 {
  A, B
}
enum E1 {
  A, B
}
class ETest {
  private E0 fld = E0.A;
}
public class EnumTroubleToo {
  public static void main(String... args) {
    try {
      ETest test = new ETest();
      Field f = test.getClass().getDeclaredField("fld");
      f.setAccessible(true);
      f.set(test, E1.A); // IllegalArgumentException
      // production code should handle these exceptions more gracefully
    } catch (NoSuchFieldException x) {
      x.printStackTrace();
    } catch (IllegalAccessException x) {
      x.printStackTrace();
    }
  }
}





Deal with Enum Type in reflection

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import static java.lang.System.out;
import java.lang.reflect.Field;
import java.util.Arrays;
enum Tweedle {
  DEE, DUM
}
public class Book {
  public long chapters = 0;
  public String[] characters = { "Alice", "White Rabbit" };
  public Tweedle twin = Tweedle.DEE;
  public static void main(String... args) {
    Book book = new Book();
    String fmt = "%6S:  %-12s = %s%n";
    try {
      Class<?> c = book.getClass();
      Field chap = c.getDeclaredField("chapters");
      out.format(fmt, "before", "chapters", book.chapters);
      chap.setLong(book, 12);
      out.format(fmt, "after", "chapters", chap.getLong(book));
      Field chars = c.getDeclaredField("characters");
      out.format(fmt, "before", "characters", Arrays.asList(book.characters));
      String[] newChars = { "Queen", "King" };
      chars.set(book, newChars);
      out.format(fmt, "after", "characters", Arrays.asList(book.characters));
      Field t = c.getDeclaredField("twin");
      out.format(fmt, "before", "twin", book.twin);
      t.set(book, Tweedle.DUM);
      out.format(fmt, "after", "twin", t.get(book));
      // production code should handle these exceptions more gracefully
    } catch (NoSuchFieldException x) {
      x.printStackTrace();
    } catch (IllegalAccessException x) {
      x.printStackTrace();
    }
  }
}





Enum Spy

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import static java.lang.System.out;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class EnumSpy {
  private static final String fmt = "  %11s:  %s %s%n";
  public static void main(String... args) {
    try {
      Class<?> c = Class.forName(args[0]);
      if (!c.isEnum()) {
        out.format("%s is not an enum type%n", c);
        return;
      }
      out.format("Class:  %s%n", c);
      Field[] flds = c.getDeclaredFields();
      List<Field> cst = new ArrayList<Field>(); // enum constants
      List<Field> mbr = new ArrayList<Field>(); // member fields
      for (Field f : flds) {
        if (f.isEnumConstant())
          cst.add(f);
        else
          mbr.add(f);
      }
      if (!cst.isEmpty())
        print(cst, "Constant");
      if (!mbr.isEmpty())
        print(mbr, "Field");
      Constructor[] ctors = c.getDeclaredConstructors();
      for (Constructor ctor : ctors) {
        out.format(fmt, "Constructor", ctor.toGenericString(), synthetic(ctor));
      }
      Method[] mths = c.getDeclaredMethods();
      for (Method m : mths) {
        out.format(fmt, "Method", m.toGenericString(), synthetic(m));
      }
      // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    }
  }
  private static void print(List<Field> lst, String s) {
    for (Field f : lst) {
      out.format(fmt, s, f.toGenericString(), synthetic(f));
    }
  }
  private static String synthetic(Member m) {
    return (m.isSynthetic() ? "[ synthetic ]" : "");
  }
}





Enum type as class

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import static java.lang.System.out;
import java.util.Arrays;
enum Eon {
  HADEAN, ARCHAEAN, PROTEROZOIC, PHANEROZOIC
}
public class EnumConstants {
  public static void main(String... args) {
    try {
      Class<?> c = (args.length == 0 ? Eon.class : Class.forName(args[0]));
      out.format("Enum name:  %s%nEnum constants:  %s%n", c.getName(), Arrays
          .asList(c.getEnumConstants()));
      if (c == Eon.class)
        out.format("  Eon.values():  %s%n", Arrays.asList(Eon.values()));
      // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    }
  }
}





Get and set value of a Enum type field

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import static java.lang.System.out;
import java.lang.reflect.Field;
enum TraceLevel {
  OFF, LOW, MEDIUM, HIGH, DEBUG
}
class MyServer {
  private TraceLevel level = TraceLevel.OFF;
}
public class SetTrace {
  public static void main(String... args) {
    TraceLevel newLevel = TraceLevel.valueOf(args[0]);
    try {
      MyServer svr = new MyServer();
      Class<?> c = svr.getClass();
      Field f = c.getDeclaredField("level");
      f.setAccessible(true);
      TraceLevel oldLevel = (TraceLevel) f.get(svr);
      out.format("Original trace level:  %s%n", oldLevel);
      if (oldLevel != newLevel) {
        f.set(svr, newLevel);
        out.format("    New  trace level:  %s%n", f.get(svr));
      }
      // production code should handle these exceptions more gracefully
    } catch (IllegalArgumentException x) {
      x.printStackTrace();
    } catch (IllegalAccessException x) {
      x.printStackTrace();
    } catch (NoSuchFieldException x) {
      x.printStackTrace();
    }
  }
}





Get declared methods for enum class

import java.lang.reflect.Method;
import org.xml.sax.XMLReader;
public class GetMethod {
  public static void main(String[] args) {
    Method[] ms = String.class.getMethods();
    for (int i = 0; i < ms.length; i++) {
      // System.out.println(ms[i].getName());
    }
    Method[] ims = XMLReader.class.getMethods();
    for (int i = 0; i < ims.length; i++) {
      // System.out.println(ims[i].getName());
    }
    Method[] sms = Size.class.getMethods();
    for (int i = 0; i < sms.length; i++) {
      // System.out.println(sms[i].getName());
    }
    String pc = new String();
    try {
      Method setCpu = String.class.getMethod("toString", String.class);
      setCpu.invoke(pc, "Intel 3.0");
      System.out.println(pc.toString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
enum Size {
  S, M, L, XL, XXL, XXXL;
}





Is it an enum

import org.xml.sax.XMLReader;

public class IsEnum {
    public static void main(String[] args) {
        System.out.println(Size.class.isEnum());
        System.out.println(String.class.isEnum());
        System.out.println(String.class.isInstance("Test"));     
        System.out.println(XMLReader.class.isInterface());          
    }
}
enum Size {
  S, M, L, XL, XXL, XXXL;
}