|
NOTA: La traducción de esta documentación es un esfuerzo personal y voluntario, no es un documento oficial de Sun Microsystems
ni Oracle ni está patrocinado por ninguna de estas empresas. Los documentos originales (en inglés) están disponibles en:
http://java.sun.com/docs/books/tutorial/.
Dirija cualquier comentario, petición, felicitación, etc. a tutorialesjava_@RROBA_codexion.com. |
Si desea ayudar a mantener en funcionamiento esta web, colaborar con la traducción de estos documentos o necesita que se traduzca algĂșn capĂtulo en concreto puede realizar una donación directa mediante Paypal:
|
The entry point for all reflection operations isjava.lang.Class. With the exception ofjava.lang.reflect.ReflectPermission, none of the classes injava.lang.reflecthave public constructors. To get to these classes, it is necessary to invoke appropriate methods onClass. There are several ways to get aClassdepending on whether the code has access to an object, the name of class, a type, or an existingClass.Object.getClass()
If an instance of an object is available, then the simplest way to get itsClassis to invokeObject.getClass(). Of course, this only works for reference types which all inherit fromObject. Some examples follow.Returns theClass c = "foo".getClass();ClassforStringThere is a unique console associated with the virtual machine which is returned by theClass c = System.console().getClass();staticmethodSystem.console(). The value returned bygetClass()is theClasscorresponding tojava.io.Console.enum E { A, B } Class c = A.getClass();Ais is an instance of the enumE; thusgetClass()returns theClasscorresponding to the enumeration typeE.Since arrays arebyte[] bytes = new byte[1024]; Class c = bytes.getClass();Objects, it is also possible to invokegetClass()on an instance of an array. The returnedClasscorresponds to an array with component typebyte.In this case,import java.util.HashSet; import java.util.Set; Set<String> s = new HashSet<String>(); Class c = s.getClass();java.util.Setis an interface to an object of typejava.util.HashSet. The value returned bygetClass()is the class corresponding tojava.util.HashSet.The .class Syntax
If the type is available but there is no instance then it is possible to obtain aClassby appending".class"to the name of the type. This is also the easiest way to obtain theClassfor a primitive type.Note that the statementboolean b; Class c = b.getClass(); // compile-time error Class c = boolean.class; // correctboolean.getClass()would produce a compile-time error because abooleanis a primitive type and cannot be dereferenced. The.classsyntax returns theClasscorresponding to the typeboolean.The variableClass c = java.io.PrintStream.class;cwill be theClasscorresponding to the typejava.io.PrintStream.TheClass c = int[][][].class;.classsyntax may be used to retrieve aClasscorresponding to a multi-dimensional array of a given type.Class.forName()
If the fully-qualified name of a class is available, it is possible to get the correspondingClassusing the static methodClass.forName(). This cannot be used for primitive types. The syntax for names of array classes is described byClass.getName(). This syntax is applicable to references and primitive types.This statement will create a class from the given fully-qualified name.Class c = Class.forName("com.duke.MyLocaleServiceProvider");The variableCLass cDoubleArray = Class.forName("[D"); Class cStringArray = Class.forName("[[Ljava.lang.String;");cDoubleArraywill contain theClasscorresponding to an array of primitive typedouble(i.e. the same asdouble[].class). ThecStringArrayvariable will contain theClasscorresponding to a two-dimensional array ofString(i.e. identical toString[][].class).TYPE Field for Primitive Type Wrappers
The.classsyntax is a more convenient and the preferred way to obtain theClassfor a primitive type; however there is another way to acquire theClass. Each of the primitive types andvoidhas a wrapper class injava.langthat is used for boxing of primitive types to reference types. Each wrapper class contains a field namedTYPEwhich is equal to theClassfor the primitive type being wrapped.There is a classClass c = Double.TYPE;java.lang.Doublewhich is used to wrap the primitive typedoublewhenever anObjectis required. The value ofDouble.TYPEis identical to that ofdouble.class.Class c = Void.TYPE;Void.TYPEis identical tovoid.class.Methods that Return Classes
There are several Reflection APIs which return classes but these may only be accessed if aClasshas already been obtained either directly or indirectly.
Class.getSuperclass()- Returns the super class for the given class.
The super class ofClass c = javax.swing.JButton.class.getSuperclass();javax.swing.JButtonisjavax.swing.AbstractButton.
Class.getClasses()- Returns all the public classes, interfaces, and enums that are members of the class including inherited members.
Class<?>[] c = Character.class.getClasses();Charactercontains two member classesCharacter.SubsetandCharacter.UnicodeBlock.
Class.getDeclaredClasses()- Returns all of the classes interfaces, and enums that are explicitly declared in this class.
Class<?>[] c = Character.class.getDeclaredClasses();Charactercontains two public member classesCharacter.SubsetandCharacter.UnicodeBlockand one private classCharacter.CharacterCache.
{Class, java.lang.reflect. {Field,Method,Constructor} }.getDeclaringClass()- Returns the
Classin which these members were declared. Anonymous classes will not have a declaring class but will have an enclosing class.The fieldimport java.lang.reflect.Field; Field f = System.class.getField("out"); Class c = f.getDeclaringClass();outis declared inSystem.The declaring class of the anonymous class defined bypublic class MyClass { static Object o = new Object() { public void m() {} }; static Class<c> = o.getClass().getEnclosingClass(); }oisnull.
Class.getEnclosingClass()- Returns the immediately enclosing class of the class.
The enclosing class of the enumClass c = Thread.State.class().getEnclosingClass();Thread.StateisThread.The anonymous class defined bypublic class MyClass { static Object o = new Object() { public void m() {} }; static Class<c> = o.getClass().getEnclosingClass(); }ois enclosed byMyClass.