Java by API/java.lang.reflect/Field

Материал из Java эксперт
Версия от 14:39, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Field: Class<?> getType()

  
import java.lang.reflect.Field;
public class Main {
  public static void initIntFields(final Object obj) {
    try {
      Field[] fields = obj.getClass().getDeclaredFields();
      for (int idx = 0; idx < fields.length; idx++) {
        if (fields[idx].getType() == int.class) {
          fields[idx].setAccessible(true);
          fields[idx].setInt(obj, 0);
        }
      }
    } catch (final IllegalAccessException ex) {
      throw new RuntimeException(ex);
    }
  }
  public static final void main(final String[] args) {
    Integer value = new Integer("123");
    System.out.println("Before: " + value);
    initIntFields(value);
    System.out.println("After: " + value);
  }
}





Field: getAnnotation(Class<DataField> annotationClass)

 
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
public class Main {
  public static void main(String[] args) {
    Class d = DataBean.class;
    Field fs[] = d.getFields();
    for (Field f : fs) {
      System.out.println(f);
      Annotation a = f.getAnnotation(DataField.class);
      if (a != null) {
        System.out.println(f.getName());
      }
    }
  }
}
class DataBean {
  @DataField
  public String name;
  @DataField
  public String data;
  public String description;
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface DataField {
}





Field: getDouble(Object obj)

 
import java.lang.reflect.Field;
public class Main {
  public static void main(String[] args) throws Exception {
    Object clazz = new TestClass();
    String lookingForValue = "firstValue";
    Field field = clazz.getClass().getField(lookingForValue);
    Class clazzType = field.getType();
    if (clazzType.toString().equals("double"))
      System.out.println(field.getDouble(clazz));
    else if (clazzType.toString().equals("int"))
      System.out.println(field.getInt(clazz));
    
    //System.out.println(field.get(clazz));
  }
}
class TestClass {
  public double firstValue = 3.14;
}





Field: getGenericType()

 
/*
 * 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;
import java.util.List;
public class Main<T> {
  public boolean[][] b = { { false, false }, { true, true } };
  public String name = "Alice";
  public List<Integer> list;
  public T val;
  public static void main(String... args) {
    try {
      Class<?> c = Class.forName("FieldSpy");
      Field f = c.getField("name");
      System.out.format("Type: %s%n", f.getType());
      System.out.format("GenericType: %s%n", f.getGenericType());
      // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    } catch (NoSuchFieldException x) {
      x.printStackTrace();
    }
  }
}





Field: getInt(Object obj)

 
import java.lang.reflect.Field;
public class Main {
  public static void main(String[] args) throws Exception {
    Object clazz = new TestClass();
    String lookingForValue = "firstValue";
    Field field = clazz.getClass().getField(lookingForValue);
    Class clazzType = field.getType();
    if (clazzType.toString().equals("double"))
      System.out.println(field.getDouble(clazz));
    else if (clazzType.toString().equals("int"))
      System.out.println(field.getInt(clazz));
    
    //System.out.println(field.get(clazz));
  }
}
class TestClass {
  public double firstValue = 3.14;
}





Field: getModifiers()

 

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class Main {
  public static void main(String[] args) {
    String name = "java.util.Date";
    try {
      Class cl = Class.forName(name);
      System.out.println("class " + name);
      System.out.println("Its methods:");
      printFields(cl);
      System.out.println();
    } catch (ClassNotFoundException e) {
      System.out.println("Class not found.");
    }
  }
  public static void printFields(Class cl) {
    Field[] fields = cl.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
      Field f = fields[i];
      Class type = f.getType();
      String name = f.getName();
      System.out.print(Modifier.toString(f.getModifiers()));
      System.out.println(" " + type.getName() + " " + name + ";");
    }
  }
}





Field: get(Object obj)

 
import java.lang.reflect.Field;
import java.util.Date;
public class Main {
  public static void main(String[] args) throws Exception {
    Bean demo = new Bean();
    Class clazz = demo.getClass();
    Field field = clazz.getField("id");
    field.set(demo, new Long(10));
    Object value = field.get(demo);
    System.out.println("Value = " + value);
    field = clazz.getField("now");
    field.set(null, new Date());
    value = field.get(null);
    System.out.println("Value = " + value);
  }
}
class Bean {
  public static Date now;
  public Long id;
  public String name;
}





Field: isEnumConstant()

 
/*
 * 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.lang.reflect.Modifier;
enum Spy {
  BLACK, WHITE
}
public class Main {
  volatile int share;
  int instance;
  class Inner {
  }
  public static void main(String... args) {
    try {
      Class<?> c = Class.forName(args[0]);
      int searchMods = 0x0;
      for (int i = 1; i < args.length; i++) {
        searchMods |= modifierFromString(args[i]);
      }
      Field[] flds = c.getDeclaredFields();
      out.format("Fields in Class "%s" containing modifiers:  %s%n", c
          .getName(), Modifier.toString(searchMods));
      boolean found = false;
      for (Field f : flds) {
        int foundMods = f.getModifiers();
        // Require all of the requested modifiers to be present
        if ((foundMods & searchMods) == searchMods) {
          out.format("%-8s [ synthetic=%-5b enum_constant=%-5b ]%n", f
              .getName(), f.isSynthetic(), f.isEnumConstant());
          found = true;
        }
      }
      if (!found) {
        out.format("No matching fields%n");
      }
      // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    }
  }
  private static int modifierFromString(String s) {
    int m = 0x0;
    if ("public".equals(s))
      m |= Modifier.PUBLIC;
    else if ("protected".equals(s))
      m |= Modifier.PROTECTED;
    else if ("private".equals(s))
      m |= Modifier.PRIVATE;
    else if ("static".equals(s))
      m |= Modifier.STATIC;
    else if ("final".equals(s))
      m |= Modifier.FINAL;
    else if ("transient".equals(s))
      m |= Modifier.TRANSIENT;
    else if ("volatile".equals(s))
      m |= Modifier.VOLATILE;
    return m;
  }
}





Field: isSynthetic()

 
/*
 * 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.lang.reflect.Modifier;
enum Spy {
  BLACK, WHITE
}
public class Main {
  volatile int share;
  int instance;
  class Inner {
  }
  public static void main(String... args) {
    try {
      Class<?> c = Class.forName(args[0]);
      int searchMods = 0x0;
      for (int i = 1; i < args.length; i++) {
        searchMods |= modifierFromString(args[i]);
      }
      Field[] flds = c.getDeclaredFields();
      out.format("Fields in Class "%s" containing modifiers:  %s%n", c
          .getName(), Modifier.toString(searchMods));
      boolean found = false;
      for (Field f : flds) {
        int foundMods = f.getModifiers();
        // Require all of the requested modifiers to be present
        if ((foundMods & searchMods) == searchMods) {
          out.format("%-8s [ synthetic=%-5b enum_constant=%-5b ]%n", f
              .getName(), f.isSynthetic(), f.isEnumConstant());
          found = true;
        }
      }
      if (!found) {
        out.format("No matching fields%n");
      }
      // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    }
  }
  private static int modifierFromString(String s) {
    int m = 0x0;
    if ("public".equals(s))
      m |= Modifier.PUBLIC;
    else if ("protected".equals(s))
      m |= Modifier.PROTECTED;
    else if ("private".equals(s))
      m |= Modifier.PRIVATE;
    else if ("static".equals(s))
      m |= Modifier.STATIC;
    else if ("final".equals(s))
      m |= Modifier.FINAL;
    else if ("transient".equals(s))
      m |= Modifier.TRANSIENT;
    else if ("volatile".equals(s))
      m |= Modifier.VOLATILE;
    return m;
  }
}





Field: setAccessible(boolean flag)

 

/*
 * 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;
public class Main {
  public final boolean b = true;
  public static void main(String... args) {
    Main ft = new Main();
    try {
      Class<?> c = ft.getClass();
      Field f = c.getDeclaredField("b");
       f.setAccessible(true); // solution
      f.setBoolean(ft, Boolean.FALSE); // IllegalAccessException
      // production code should handle these exceptions more gracefully
    } catch (NoSuchFieldException x) {
      x.printStackTrace();
    } catch (IllegalArgumentException x) {
      x.printStackTrace();
    } catch (IllegalAccessException x) {
      x.printStackTrace();
    }
  }
}





Field: setBoolean(Object obj, boolean z)

 
/*
 * 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;
public class Main {
  public final boolean b = true;
  public static void main(String... args) {
    Main ft = new Main();
    try {
      Class<?> c = ft.getClass();
      Field f = c.getDeclaredField("b");
       f.setAccessible(true); // solution
      f.setBoolean(ft, Boolean.FALSE); // IllegalAccessException
      // production code should handle these exceptions more gracefully
    } catch (NoSuchFieldException x) {
      x.printStackTrace();
    } catch (IllegalArgumentException x) {
      x.printStackTrace();
    } catch (IllegalAccessException x) {
      x.printStackTrace();
    }
  }
}





Field: setInt(Object obj, int i)

  
/*
Before: [a=21.25, b=54.5, c=5665, d=2043, e=3121, f=1019]
After: [a=21.25, b=54.5, c=0, d=0, e=0, f=0]
*/
/*
 *
 * This software is granted under the terms of the Common Public License,
 * CPL, which may be found at the following URL:
 * http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm
 *
 * Copyright(c) 2003-2005 by the authors indicated in the @author tags.
 * All Rights are Reserved by the various authors.
 *
########## DO NOT EDIT ABOVE THIS LINE ########## */
import java.lang.reflect.Field;
/**  
 * Demonstrates how to set public field objects.
 *
 * @author 
 * @version $Revision: 1.3 $
 */
public class HiddenFieldModification {
  /** 
   * Sets all int fields in an object to 0.
   *
   * @param obj The object to operate on.
   *
   * @throws RuntimeException If there is a reflection problem.
   */
  public static void initIntFields(final Object obj) {
    try {
      Field[] fields = obj.getClass()
                        .getDeclaredFields();
      for (int idx = 0; idx < fields.length; idx++) {
        if (fields[idx].getType() == int.class) {
          fields[idx].setAccessible(true);
          fields[idx].setInt(obj, 0);
        }
      }
    } catch (final IllegalAccessException ex) {
      throw new RuntimeException(ex);
    }
  }
  /** 
   * Demo Method.
   *
   * @param args Command line arguments.
   */
  public static final void main(final String[] args) {
    SomeNumbers value = new SomeNumbers();
    System.out.println("Before: " + value);
    initIntFields(value);
    System.out.println("After: " + value);
  }
}
class SomeNumbers {
  /** A demo double. */
  public double a = 21.25d;
  /** A demo float. */
  public float b = 54.5f;
  /** A Demo int */
  public int c = 5665;
  /** Another demo int. */
  public int d = 2043;
  /** Another demo int. */
  protected int e = 3121;
  /** Another demo int. */
  private int f = 1019;
  /** 
   * @see java.lang.Object#toString()
   */
  public String toString() {
    return new String("[a=" + a + ", b=" + b + ", c=" + c + ", d=" + d + ", e=" + e
                      + ", f=" + f + "]");
  }
}