Java Tutorial/Reflection/Modifier
Содержание
- 1 AccessController.doPrivileged(new PrivilegedAction() )
- 2 Get all object accessible public fields
- 3 Gets a method and forces it to be accessible, even if it is not.
- 4 Listing the Modifiers of a Class Object
- 5 Listing the Modifiers of a Member Object: Field, Constructor, and Method are all subclasses of Member.
- 6 Make AccessibleObject Accessible
- 7 Make field accessible, explicitly setting it accessible
- 8 Overriding Default Access
- 9 Return true if the integer argument includes the abstract modifier, false otherwise.
- 10 Return true if the integer argument includes the final modifier, false otherwise.
- 11 Return true if the integer argument includes the private modifier, false otherwise.
- 12 Return true if the integer argument includes the protected modifier,false otherwise.
- 13 Return true if the integer argument includes the public modifier, false otherwise
- 14 Return true if the integer argument includes the static modifier, false otherwise.
- 15 Set Accessibility
- 16 whether given field is a "public static final" constant
AccessController.doPrivileged(new PrivilegedAction() )
import java.io.File;
import java.security.AccessController;
import java.security.PrivilegedAction;
public class Main {
static long getLastModified(final File f) {
return ((Long)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return new Long(f.lastModified());
}
})).longValue();
}
}
Get all object accessible public fields
import java.lang.reflect.Field;
import java.util.Date;
public class Main {
public static void main(String[] args) throws Exception {
GetFields object = new GetFields();
Class clazz = object.getClass();
// Get all object accessible public fields.
Field[] fields = clazz.getFields();
System.out.println("Number of fields = " + fields.length);
for (Field field : fields) {
System.out.println("Field name = " + field.getName());
System.out.println("Field type = " + field.getType().getName());
}
Field field = clazz.getField("id");
System.out.println("Field name = " + field.getName());
System.out.println("Field type = " + field.getType().getName());
}
}
class GetFields {
public Long id;
protected String name;
private Date birthDate;
Double weight;
}
Gets a method and forces it to be accessible, even if it is not.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {
/**
* Gets a method and forces it to be accessible, even if it is not.
*
* @param clazz The class from which the method will be got.
* @param methodName The name of the method.
* @param parameterTypes The parameter types that the method must match.
* @return The method, if it is found.
* @since 2.0.7
*/
public static Method getForcedAccessibleMethod(Class<?> clazz,
String methodName, Class<?>... parameterTypes) {
Method method;
try {
method = clazz.getMethod(methodName, parameterTypes);
} catch (SecurityException e) {
throw new RuntimeException("Cannot access method ""
+ methodName + "" in class "" + clazz.getName()
+ "" for security reasons", e);
} catch (NoSuchMethodException e) {
throw new RuntimeException("The method ""
+ methodName + "" in class "" + clazz.getName()
+ "" does not exist", e);
}
if (!method.isAccessible()) {
method.setAccessible(true);
}
return method;
}
}
Listing the Modifiers of a Class Object
import java.lang.reflect.Modifier;
public class Main {
public static void main(String[] argv) throws Exception {
int mods = String.class.getModifiers();
if (Modifier.isPublic(mods)) {
System.out.println("class is public");
}
}
}
Listing the Modifiers of a Member Object: Field, Constructor, and Method are all subclasses of Member.
import java.lang.reflect.Modifier;
public class Main {
public static void main(String[] argv) throws Exception {
int mods = String.class.getDeclaredMethods()[0].getModifiers();
if (Modifier.isPublic(mods)) {
System.out.println("member is public");
}
}
}
Make AccessibleObject Accessible
import java.lang.reflect.AccessibleObject;
import java.security.AccessController;
import java.security.PrivilegedAction;
public class Utils {
public static void makeAccessible( final AccessibleObject object ) {
if (!object.isAccessible()) {
if (System.getSecurityManager() == null) {
object.setAccessible(true);
} else {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
object.setAccessible(true);
return null;
}
});
}
}
}
}
Make field accessible, explicitly setting it accessible
/*
* Copyright 2002-2008 the original author or authors.
*
* 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.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* Simple utility class for working with the reflection API and handling
* reflection exceptions.
*
* Only intended for internal use.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @author Rod Johnson
* @author Costin Leau
* @since 1.2.2
*/
public abstract class ReflectionUtils {
/**
* Make the given field accessible, explicitly setting it accessible if necessary.
* The <code>setAccessible(true)</code> method is only called when actually necessary,
* to avoid unnecessary conflicts with a JVM SecurityManager (if active).
* @param field the field to make accessible
* @see java.lang.reflect.Field#setAccessible
*/
public static void makeAccessible(Field field) {
if (!Modifier.isPublic(field.getModifiers()) ||
!Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
field.setAccessible(true);
}
}
}
Overriding Default Access
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] argv) throws Exception {
Class cls = java.lang.String.class;
Method method = cls.getMethods()[0];
Field field = cls.getFields()[0];
Constructor constructor = cls.getConstructors()[0];
field.setAccessible(true);
constructor.setAccessible(true);
method.setAccessible(true);
}
}
Return true if the integer argument includes the abstract modifier, false otherwise.
import java.lang.reflect.Modifier;
public class Main {
public static void main(String[] args) throws Exception {
getClassModifier(String.class);
getClassModifier(TestA.class);
getClassModifier(TestB.class);
}
private static void getClassModifier(Class clazz) {
int modifier = clazz.getModifiers();
if (Modifier.isAbstract(modifier)) {
System.out.println(clazz.getName() + " class modifier is abstract");
}
}
protected static final class TestA {
}
private abstract class TestB {
}
}
Return true if the integer argument includes the final modifier, false otherwise.
import java.lang.reflect.Modifier;
public class Main {
public static void main(String[] args) throws Exception {
getClassModifier(String.class);
getClassModifier(TestA.class);
getClassModifier(TestB.class);
}
private static void getClassModifier(Class clazz) {
int modifier = clazz.getModifiers();
if (Modifier.isFinal(modifier)) {
System.out.println(clazz.getName() + " class modifier is final");
}
}
protected static final class TestA {
}
private abstract class TestB {
}
}
Return true if the integer argument includes the private modifier, false otherwise.
import java.lang.reflect.Modifier;
public class Main {
public static void main(String[] args) throws Exception {
getClassModifier(String.class);
getClassModifier(TestA.class);
getClassModifier(TestB.class);
}
private static void getClassModifier(Class clazz) {
int modifier = clazz.getModifiers();
if (Modifier.isPrivate(modifier)) {
System.out.println(clazz.getName() + " class modifier is private");
}
}
protected static final class TestA {
}
private abstract class TestB {
}
}
Return true if the integer argument includes the protected modifier,false otherwise.
import java.lang.reflect.Modifier;
public class Main {
public static void main(String[] args) throws Exception {
getClassModifier(String.class);
getClassModifier(TestA.class);
getClassModifier(TestB.class);
}
private static void getClassModifier(Class clazz) {
int modifier = clazz.getModifiers();
if (Modifier.isProtected(modifier)) {
System.out.println(clazz.getName() + " class modifier is protected");
}
}
protected static final class TestA {
}
private abstract class TestB {
}
}
Return true if the integer argument includes the public modifier, false otherwise
import java.lang.reflect.Modifier;
public class Main {
public static void main(String[] args) throws Exception {
getClassModifier(String.class);
getClassModifier(TestA.class);
getClassModifier(TestB.class);
}
private static void getClassModifier(Class clazz) {
int modifier = clazz.getModifiers();
if (Modifier.isPublic(modifier)) {
System.out.println(clazz.getName() + " class modifier is public");
}
}
protected static final class TestA {
}
private abstract class TestB {
}
}
Return true if the integer argument includes the static modifier, false otherwise.
import java.lang.reflect.Modifier;
public class Main {
public static void main(String[] args) throws Exception {
getClassModifier(String.class);
getClassModifier(TestA.class);
getClassModifier(TestB.class);
}
private static void getClassModifier(Class clazz) {
int modifier = clazz.getModifiers();
if (Modifier.isStatic(modifier)) {
System.out.println(clazz.getName() + " class modifier is static");
}
}
protected static final class TestA {
}
private abstract class TestB {
}
}
Set Accessibility
// $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 {
public static void setAccessibility(Member member) {
if ( !Modifier.isPublic( member.getModifiers() ) ) {
//Sun"s ease of use, sigh...
( ( AccessibleObject ) member ).setAccessible( true );
}
}
}
whether given field is a "public static final" constant
/*
* Copyright 2002-2008 the original author or authors.
*
* 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.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* Simple utility class for working with the reflection API and handling
* reflection exceptions.
*
* Only intended for internal use.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @author Rod Johnson
* @author Costin Leau
* @since 1.2.2
*/
public abstract class ReflectionUtils {
/**
* Determine whether the given field is a "public static final" constant.
* @param field the field to check
*/
public static boolean isPublicStaticFinal(Field field) {
int modifiers = field.getModifiers();
return (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers));
}
}