Java Tutorial/Reflection/Field
Содержание
- 1 Checks whether the specified class contains a field matching the specified name.
- 2 Get all declared fields from a class
- 3 Get a variable value from the variable name
- 4 Get the name of a primitive type
- 5 Getting and Setting the Value of a Field (assumes that the field has the type int)
- 6 Getting the Field Objects of a Class Object: By obtaining a list of all declared fields.
- 7 Getting the Field Objects of a Class Object: By obtaining a list of all public fields, both declared and inherited.
- 8 Getting the Field Objects of a Class Object: By obtaining a particular Field object.
- 9 Reflect All
- 10 Reflection, Introspection, and Naming
- 11 Retrieving a Predefined Color by Name
- 12 Return a list of all fields (whatever access status, and on whatever superclass they were defined) that can be found on this class.
- 13 Return Retrurns the Type of the given Field or Method
- 14 System class reflection
Checks whether the specified class contains a field matching the specified name.
// $Id: ReflectionHelper.java 16271 2009-04-07 20:20:12Z hardy.ferentschik $
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.beans.Introspector;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Some reflection utility methods.
*
* @author Hardy Ferentschik
*/
public class ReflectionHelper {
/**
* Checks whether the specified class contains a field matching the specified name.
*
* @param clazz The class to check.
* @param fieldName The field name.
*
* @return Returns <code>true</code> if the cass contains a field for the specified name, <code>
* false</code> otherwise.
*/
public static boolean containsField(Class<?> clazz, String fieldName) {
try {
clazz.getDeclaredField( fieldName );
return true;
}
catch ( NoSuchFieldException e ) {
return false;
}
}
}
Get all declared fields from a class
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Main{
public static void main(String args[]) throws Exception {
Class c = Class.forName("MyClass");
System.out.println("\nFields:");
Field fields[] = c.getDeclaredFields();
for (Field fld : fields)
System.out.println(" " + fld);
}
}
class MyClass {
private int count;
MyClass(int c) {
count = c;
}
MyClass() {
count = 0;
}
void setCount(int c) {
count = c;
}
int getCount() {
return count;
}
void showcount() {
System.out.println("count is " + count);
}
}
Get a variable value from the variable name
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;
}
Get the name of a primitive type
public class Main {
public static void main(String[] argv) throws Exception {
String name = int.class.getName(); // int
System.out.println(name);
}
}
Getting and Setting the Value of a Field (assumes that the field has the type int)
import java.lang.reflect.Field;
public class Main {
public static void main(String[] argv) throws Exception {
Class cls = java.awt.Point.class;
Field field = cls.getField("x");
// Get value
// field.getInt(object);
// Set value
// field.setInt(object, 123);
// Get value of a static field
field.getInt(null);
// Set value of a static field
field.setInt(null, 123);
}
}
Getting the Field Objects of a Class Object: By obtaining a list of all declared fields.
import java.lang.reflect.Field;
public class Main {
public static void main(String[] argv) throws Exception {
Class cls = java.awt.Point.class;
Field[] fields = cls.getDeclaredFields();
}
}
Getting the Field Objects of a Class Object: By obtaining a list of all public fields, both declared and inherited.
import java.lang.reflect.Field;
public class Main {
public static void main(String[] argv) throws Exception {
Class cls = java.awt.Point.class;
Field[] fields = cls.getFields();
for (int i = 0; i < fields.length; i++) {
Class type = fields[i].getType();
System.out.println(fields[i]);
}
}
}
Getting the Field Objects of a Class Object: By obtaining a particular Field object.
import java.lang.reflect.Field;
public class Main {
public static void main(String[] argv) throws Exception {
Class cls = java.awt.Point.class;
Field field = cls.getField("x");
System.out.println(field);
}
}
Reflect All
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class ReflectApp {
public static void main(String args[]) {
String parm = args[0];
Class className = void.class;
try {
className = Class.forName(parm);
} catch (ClassNotFoundException ex) {
System.out.println("Not a class or interface.");
System.exit(0);
}
describeClassOrInterface(className, parm);
}
static void describeClassOrInterface(Class className, String name) {
displayModifiers(className.getModifiers());
displayFields(className.getDeclaredFields());
displayMethods(className.getDeclaredMethods());
if (className.isInterface()) {
System.out.println("Interface: " + name);
} else {
System.out.println("Class: " + name);
displayInterfaces(className.getInterfaces());
displayConstructors(className.getDeclaredConstructors());
}
}
static void displayModifiers(int m) {
System.out.println("Modifiers: " + Modifier.toString(m));
}
static void displayInterfaces(Class[] interfaces) {
if (interfaces.length > 0) {
System.out.println("Interfaces: ");
for (int i = 0; i < interfaces.length; ++i)
System.out.println(interfaces[i].getName());
}
}
static void displayFields(Field[] fields) {
if (fields.length > 0) {
System.out.println("Fields: ");
for (int i = 0; i < fields.length; ++i)
System.out.println(fields[i].toString());
}
}
static void displayConstructors(Constructor[] constructors) {
if (constructors.length > 0) {
System.out.println("Constructors: ");
for (int i = 0; i < constructors.length; ++i)
System.out.println(constructors[i].toString());
}
}
static void displayMethods(Method[] methods) {
if (methods.length > 0) {
System.out.println("Methods: ");
for (int i = 0; i < methods.length; ++i)
System.out.println(methods[i].toString());
}
}
}
Reflection, Introspection, and Naming
import java.lang.reflect.Field;
public class RectangleFields {
public static void main(String args[]) {
Class rectClass = null;
Field rectField[] = null;
try {
rectClass = Class.forName("java.awt.Rectangle");
rectField = rectClass.getDeclaredFields();
} catch (SecurityException se) {
System.out.println("Access to Rectangle fields denied");
} catch (ClassNotFoundException cnfe) {
System.out.println("Didn"t find the Rectangle class");
}
System.out.println("Fields in Rectangle are:");
for (int i = 0; i < rectField.length; i++) {
System.out.println(rectField[i].toString());
}
}
}
Retrieving a Predefined Color by Name
import java.awt.Color;
import java.lang.reflect.Field;
public class Main {
public static void main(String[] argv) throws Exception {
System.out.println(getColor("blue"));
}
public static Color getColor(String colorName) {
try {
Field field = Class.forName("java.awt.Color").getField(colorName);
return (Color) field.get(null);
} catch (Exception e) {
return null;
}
}
}
Return a list of all fields (whatever access status, and on whatever superclass they were defined) that can be found on this class.
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
/*
* Copyright 2005 Joe Walker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class Main {
/**
* Return a list of all fields (whatever access status, and on whatever
* superclass they were defined) that can be found on this class.
* This is like a union of {@link Class#getDeclaredFields()} which
* ignores and super-classes, and {@link Class#getFields()} which ignored
* non-public fields
* @param clazz The class to introspect
* @return The complete list of fields
*/
public static Field[] getAllFields(Class<?> clazz)
{
List<Class<?>> classes = getAllSuperclasses(clazz);
classes.add(clazz);
return getAllFields(classes);
}
/**
* As {@link #getAllFields(Class)} but acts on a list of {@link Class}s and
* uses only {@link Class#getDeclaredFields()}.
* @param classes The list of classes to reflect on
* @return The complete list of fields
*/
private static Field[] getAllFields(List<Class<?>> classes)
{
Set<Field> fields = new HashSet<Field>();
for (Class<?> clazz : classes)
{
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
}
return fields.toArray(new Field[fields.size()]);
}
/**
* Return a List of super-classes for the given class.
* @param clazz the class to look up
* @return the List of super-classes in order going up from this one
*/
public static List<Class<?>> getAllSuperclasses(Class<?> clazz)
{
List<Class<?>> classes = new ArrayList<Class<?>>();
Class<?> superclass = clazz.getSuperclass();
while (superclass != null)
{
classes.add(superclass);
superclass = superclass.getSuperclass();
}
return classes;
}
}
Return Retrurns the Type of the given Field or Method
// $Id: ReflectionHelper.java 16271 2009-04-07 20:20:12Z hardy.ferentschik $
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.beans.Introspector;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Some reflection utility methods.
*
* @author Hardy Ferentschik
*/
public class ReflectionHelper {
/**
* @param member The <code>Member</code> instance for which to retrieve the type.
*
* @return Retrurns the <code>Type</code> of the given <code>Field</code> or <code>Method</code>.
*
* @throws IllegalArgumentException in case <code>member</code> is not a <code>Field</code> or <code>Method</code>.
*/
public static Type typeOf(Member member) {
if ( member instanceof Field ) {
return ( ( Field ) member ).getGenericType();
}
if ( member instanceof Method ) {
return ( ( Method ) member ).getGenericReturnType();
}
throw new IllegalArgumentException( "Member " + member + " is neither a field nor a method" );
}
}
System class reflection
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionDemo1 {
public static void main(String args[]) {
try {
Class c = Class.forName("java.awt.Dimension");
System.out.println("Constructors:");
Constructor constructors[] = c.getConstructors();
for (int i = 0; i < constructors.length; i++) {
System.out.println(" " + constructors[i]);
}
System.out.println("Fields:");
Field fields[] = c.getFields();
for (int i = 0; i < fields.length; i++) {
System.out.println(" " + fields[i]);
}
System.out.println("Methods:");
Method methods[] = c.getMethods();
for (int i = 0; i < methods.length; i++) {
System.out.println(" " + methods[i]);
}
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}