A class may be declared with one or more modifiers which affect its runtime behavior:Not all modifiers are allowed on all classes, for example an interface cannot be
- Access modifiers:
public,protected, andprivate- Modifier requiring override:
abstract- Modifier restricting to one instance:
static- Modifier prohibiting value modification:
final- Modifier forcing strict floating point behavior:
strictfp- Annotations
finaland an enum cannot beabstract.java.lang.reflect.Modifiercontains declarations for all possible modifiers. It also contains methods which may be used to decode the set of modifiers returned byClass.getModifiers().The
example shows how to obtain the declaration components of a class including the modifiers, generic type parameters, implemented interfaces, and the inheritance path. SinceClassDeclarationSpyClassimplements thejava.lang.reflect.AnnotatedElementinterface it is also possible to query the runtime annotations.A few samples of the output follows. User input is in italics./* * 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.annotation.Annotation; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.Arrays; import java.util.ArrayList; import java.util.List; import static java.lang.System.out; public class ClassDeclarationSpy { public static void main(String... args) { try { Class<?> c = Class.forName(args[0]); out.format("Class:%n %s%n%n", c.getCanonicalName()); out.format("Modifiers:%n %s%n%n", Modifier.toString(c.getModifiers())); out.format("Type Parameters:%n"); TypeVariable[] tv = c.getTypeParameters(); if (tv.length != 0) { out.format(" "); for (TypeVariable t : tv) out.format("%s ", t.getName()); out.format("%n%n"); } else { out.format(" -- No Type Parameters --%n%n"); } out.format("Implemented Interfaces:%n"); Type[] intfs = c.getGenericInterfaces(); if (intfs.length != 0) { for (Type intf : intfs) out.format(" %s%n", intf.toString()); out.format("%n"); } else { out.format(" -- No Implemented Interfaces --%n%n"); } out.format("Inheritance Path:%n"); List<Class> l = new ArrayList<Class>(); printAncestor(c, l); if (l.size() != 0) { for (Class<?> cl : l) out.format(" %s%n", cl.getCanonicalName()); out.format("%n"); } else { out.format(" -- No Super Classes --%n%n"); } out.format("Annotations:%n"); Annotation[] ann = c.getAnnotations(); if (ann.length != 0) { for (Annotation a : ann) out.format(" %s%n", a.toString()); out.format("%n"); } else { out.format(" -- No Annotations --%n%n"); } // production code should handle this exception more gracefully } catch (ClassNotFoundException x) { x.printStackTrace(); } } private static void printAncestor(Class<?> c, List<Class> l) { Class<?> ancestor = c.getSuperclass(); if (ancestor != null) { l.add(ancestor); printAncestor(ancestor, l); } } }This is the actual declaration for$ java ClassDeclarationSpy java.util.concurrent.ConcurrentNavigableMap Class: java.util.concurrent.ConcurrentNavigableMap Modifiers: public abstract interface Type Parameters: K V Implemented Interfaces: java.util.concurrent.ConcurrentMap<K, V> java.util.NavigableMap<K, V> Inheritance Path: -- No Super Classes -- Annotations: -- No Annotations --java.util.concurrent.ConcurrentNavigableMapin the source code:Note that since this is an interface, it is implicitlypublic interface ConcurrentNavigableMap<K,V> extends ConcurrentMap, NavigableMap<K,V> abstract. The compiler adds this modifier for every interface. Also, this declaration contains two generic type parameters,KandV. The example code simply prints the names of these parameters, but is it possible to retrieve additional information about them using methods injava.lang.reflect.TypeVariable. Interfaces may also implement other interfaces as shown above.Since arrays are runtime objects, all of the type information is defined by the Java virtual machine. In particular, arrays implement$ java ClassDeclarationSpy "[Ljava.lang.String;" Class: java.lang.String[] Modifiers: public abstract final Type Parameters: -- No Type Parameters -- Implemented Interfaces: interface java.lang.Cloneable interface java.io.Serializable Inheritance Path: java.lang.Object Annotations: -- No Annotations --Cloneableandjava.io.Serializableand their direct superclass is alwaysObject.From the inheritance path, it may be deduced that$ java ClassDeclarationSpy java.io.InterruptedIOException Class: java.io.InterruptedIOException Modifiers: public Type Parameters: -- No Type Parameters -- Implemented Interfaces: -- No Implemented Interfaces -- Inheritance Path: java.io.IOException java.lang.Exception java.lang.Throwable java.lang.Object Annotations: -- No Annotations --java.io.InterruptedIOExceptionis a checked exception becauseRuntimeExceptionis not present.This output shows that$ java ClassDeclarationSpy java.security.Identity Class: java.security.Identity Modifiers: public abstract Type Parameters: -- No Type Parameters -- Implemented Interfaces: interface java.security.Principal interface java.io.Serializable Inheritance Path: java.lang.Object Annotations: @java.lang.Deprecated()java.security.Identity, a deprecated API, possesses the annotationjava.lang.Deprecated. This may be used by reflective code to detect deprecated APIs.
Note: Not all annotations are available via reflection. Only those which have ajava.lang.annotation.RetentionPolicyofRUNTIMEare accessible. Of the three annotations pre-defined in the language@Deprecated,@Override, and@SuppressWarningsonly@Deprecatedis available at runtime.