Download presentation
Presentation is loading. Please wait.
1
Рефлексия Макаревич Л. Г.
2
Introspection и reflection
Самоанализ и рефлексия (java.lang.Class, java.lang.reflect) Получение информации о методах, полях классов, динамическое создание объектов и классов
3
Основные возможности рефлексии
Определить тип объекта Получить данные о методах, полях, конструкторах, родительском типе, модификаторах Выделить методы и константы интерфейса Создать объекты заранее неизвестного типа Получить.установить значения полей Вызвать метод Создать массив объектов неизвестного типа, изменять значения элементов
4
Использование instanceof
class A { int i; A(int j){i = j;} } class B extends A int k; B(int j){super(j); k = j+1;} static public void main(String [] arg) A a1 = new A(88); B b1 = new B(55); System.out.println(b1 instanceof A); //true System.out.println(a1 instanceof B); //false System.out.println(c.isInstance(a1)); //true System.out.println(c.isInstance(b1)); //true System.out.println(c.isInstance(a1)); //false
5
Получение имени класса
По ссылке на объект Class c =mystery.getClass();// в Object Родительский класс JTextField t = new JTextField(); Class c = t.getClass(); Class cp = c.getSuperClass(); На стадии компиляции по имени класса Class c = Jbutton.class; Class c = boolean.class; Class c = int.class; Class c = Boolean.TYPE; // эквивалентно boolean.class На стадии выполнения по имени класса Class c = Class.forName(nameOfClass);
6
class C int java.lang.Integer import java.lang.*;
import java.lang.reflect.*; class C { public int a; private int b; public static void main(String [] arg) C m = new C(); try System.out.println(Class.forName("C")); Class c1 = int.class; System.out.println(c1); System.out.println(c1.getName()); c1= Integer.class; c1 = Integer.TYPE; System.out.println(int.class.getName()); }catch(Exception e){} String s = new String(); Class c = m.getClass(); Class sc = c.getSuperclass(); } class C int java.lang.Integer
7
Определение интерфейсов класса
Class[] getInterfaces() Determines the interfaces implemented by the class or interface represented by this object. boolean isInterface() Determines if the specified Class object represents an interface type.
8
A A is interface import java.lang.reflect.*; import java.io.*;
interface A { int aa(int a); } class SampleInterface implements A { public static void main(String[] args) { SampleInterface s = new SampleInterface(); printInterfaceNames(s); Class o = A.class; if (o.isInterface()) System.out.println(o.getName() + “ is interface"); else System.out.println(o.getName() + “ is class"); o = s.getClass(); public int aa(int a){ return a++;} static void printInterfaceNames(Object o) { Class[] theInterfaces = c.getInterfaces(); for (int i = 0; i < theInterfaces.length; i++) { String interfaceName = theInterfaces[i].getName(); System.out.println(interfaceName); A A is interface
9
java.io.DataOutput java.io.DataInput interface A { int aa(int a); }
class SampleInterface implements A { public static void main(String[] args) { RandomAccessFile r; try { r = new RandomAccessFile("int.java", "r"); SampleInterface.printInterfaceNames(r); } catch (IOException e) { System.out.println(e); public int aa(int a){ return a++;} static void printInterfaceNames(Object o) { Class c = o.getClass(); Class[] theInterfaces = c.getInterfaces(); for (int i = 0; i < theInterfaces.length; i++) { String interfaceName = theInterfaces[i].getName(); System.out.println(interfaceName); java.io.DataOutput java.io.DataInput
10
Модификаторы класса Class Modifier
static boolean isAbstract(int mod) Return true if the integer argument includes the abstract modifer, false otherwise. isFinal(int mod) Return true if the integer argument includes the final modifer, false otherwise. isInterface(int mod) Return true if the integer argument includes the interface modifer, false otherwise. isNative(int mod) Return true if the integer argument includes the native modifer, false otherwise. isPrivate(int mod) Return true if the integer argument includes the private modifer, false otherwise. isProtected(int mod) Return true if the integer argument includes the protected modifer, false otherwise. isPublic(int mod) Return true if the integer argument includes the public modifer, false otherwise. isStatic(int mod) Return true if the integer argument includes the static modifer, false otherwise. isStrict(int mod) Return true if the integer argument includes the strictfp modifer, false otherwise. isSynchronized(int mod) Return true if the integer argument includes the synchronized modifer, false otherwise. isTransient(int mod) Return true if the integer argument includes the transient modifer, false otherwise. isVolatile(int mod) Return true if the integer argument includes the volatile modifer, false otherwise. static String toString(int mod) Return a string describing the access modifier flags in the specified modifier.
11
static int ABSTRACT The int value representing the abstract modifier. FINAL The int value representing the final modifier. INTERFACE The int value representing the interface modifier. NATIVE The int value representing the native modifier. PRIVATE The int value representing the private modifier. PROTECTED The int value representing the protected modifier. PUBLIC The int value representing the public modifier. STATIC The int value representing the static modifier. STRICT The int value representing the strictfp modifier. SYNCHRONIZED The int value representing the synchronized modifier. TRANSIENT The int value representing the transient modifier. VOLATILE The int value representing the volatile modifier.
12
Класс Class int getModifiers() Returns the Java language modifiers for this class or interface, encoded in an integer.
13
class My public final java.lang.Object import java.lang.reflect.*;
{public static void main(String [] arg) { My m = new My(); try{ System.out.println(Class.forName("My")); }catch(Exception e){} String s=new String(); printModifiers(s); /*****************************/ Class c = m.getClass(); Class sc = c.getSuperclass(); while (sc != null) { String className = sc.getName(); System.out.println(className); c = sc; sc = c.getSuperclass(); } public static void printModifiers(Object o) { Class c = o.getClass(); int m = c.getModifiers(); if (Modifier.isPublic(m)) System.out.println("public"); if (Modifier.isAbstract(m)) System.out.println("abstract"); if (Modifier.isFinal(m)) System.out.println("final"); } } class My public final java.lang.Object
14
Конструкторы Class Constructor
boolean equals(Object obj) Compares this Constructor against the specified object. Class getDeclaringClass() Returns the Class object representing the class that declares the constructor represented by this Constructor object. Class[] getExceptionTypes() Returns an array of Class objects that represent the types of of exceptions declared to be thrown by the underlying constructor represented by this Constructor object. int getModifiers() Returns the Java language modifiers for the constructor represented by this Constructor object, as an integer. String getName() Returns the name of this constructor, as a string. getParameterTypes() Returns an array of Class objects that represent the formal parameter types, in declaration order, of the constructor represented by this Constructor object. hashCode() Returns a hashcode for this Constructor. Object newInstance(Object[] initargs) Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters. toString() Returns a string describing this Constructor
15
Класс Class Constructor getConstructor(Class[] parameterTypes) Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object. Constructor[] getConstructors() Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object. Class[] getDeclaredClasses() Returns an array of Class objects reflecting all the classes and interfaces declared as members of the class represented by this Class object. getDeclaredConstructor(Class[] parameterTypes) Returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object. getDeclaredConstructors() Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object.
16
( java.awt.Point java.awt.Dimension ) ( ) ( java.awt.Rectangle )
import java.lang.reflect.*; import java.awt.*; class SampleConstructor { public static void main(String[] args) { Rectangle r = new Rectangle(); showConstructors(r); } static void showConstructors(Object o) { Class c = o.getClass(); Constructor[] theConstructors = c.getConstructors(); for (int i = 0; i < theConstructors.length; i++) { System.out.print("( "); Class[] parameterTypes = theConstructors[i].getParameterTypes(); for (int k = 0; k < parameterTypes.length; k ++) { String parameterString = parameterTypes[k].getName(); System.out.print(parameterString + " "); System.out.println(")"); ( java.awt.Point java.awt.Dimension ) ( ) ( java.awt.Rectangle ) ( int int int int ) ( int int ) ( java.awt.Point ) ( java.awt.Dimension )
17
Класс Method boolean equals(Object obj) Compares this Method against the specified object. Class getDeclaringClass() Returns the Class object representing the class or interface that declares the method represented by this Method object. Class[] getExceptionTypes() Returns an array of Class objects that represent the types of the exceptions declared to be thrown by the underlying method represented by this Method object. int getModifiers() Returns the Java language modifiers for the method represented by this Method object, as an integer. String getName() Returns the name of the method represented by this Method object, as a String. getParameterTypes() Returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by this Method object. getReturnType() Returns a Class object that represents the formal return type of the method represented by this Method object. hashCode() Returns a hashcode for this Method. Object invoke(Object obj, Object[] args) Invokes the underlying method represented by this Method object, on the specified object with the specified parameters. toString() Returns a string describing this Method.
18
Класс Class Method getDeclaredMethod(String name, Class[] parameterTypes) Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object. Method[] getDeclaredMethods() Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object. Method getMethod(String name, Class[] parameterTypes) Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object. Method[] getMethods() Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and and those inherited from superclasses and superinterfaces.
19
import java.lang.reflect.*;
import java.awt.*; class SampleMethod { public static void main(String[] args) { Object p = new Object(); showMethods(p); } static void showMethods(Object o) { Class c = o.getClass(); Method[] theMethods = c.getMethods(); for (int i = 0; i < theMethods.length; i++) { String methodString = theMethods[i].getName(); System.out.println("Name: " + methodString); String returnString = theMethods[i].getReturnType().getName(); System.out.println(" Return Type: " + returnString); Class[] parameterTypes = theMethods[i].getParameterTypes(); System.out.print(" Parameter Types:"); for (int k = 0; k < parameterTypes.length; k ++) { String parameterString = parameterTypes[k].getName(); System.out.print(" " + parameterString); System.out.println(); } } } Name: hashCode Return Type: int Parameter Types: Name: getClass Return Type: java.lang.Class Name: wait Return Type: void Parameter Types: long int Parameter Types: long Name: equals Return Type: boolean Parameter Types: java.lang.Object Name: toString Return Type: java.lang.String Name: notify Name: notifyAll
20
Класс Field boolean equals(Object obj) Compares this Field against the specified object. Object get(Object obj) Returns the value of the field represented by this Field, on the specified object. getBoolean(Object obj) Gets the value of a static or instance boolean field. byte getByte(Object obj) Gets the value of a static or instance byte field. char getChar(Object obj) Gets the value of a static or instance field of type char or of another primitive type convertible to type char via a widening conversion. Class getDeclaringClass() Returns the Class object representing the class or interface that declares the field represented by this Field object. double getDouble(Object obj) Gets the value of a static or instance field of type double or of another primitive type convertible to type double via a widening conversion. float getFloat(Object obj) Gets the value of a static or instance field of type float or of another primitive type convertible to type float via a widening conversion
21
int getInt(Object obj) Gets the value of a static or instance field of type int or of another primitive type convertible to type int via a widening conversion. long getLong(Object obj) Gets the value of a static or instance field of type long or of another primitive type convertible to type long via a widening conversion. getModifiers() Returns the Java language modifiers for the field represented by this Field object, as an integer. String getName() Returns the name of the field represented by this Field object. short getShort(Object obj) Gets the value of a static or instance field of type short or of another primitive type convertible to type short via a widening conversion. Class getType() Returns a Class object that identifies the declared type for the field represented by this Field object. hashCode() Returns a hashcode for this Field. void set(Object obj, Object value) Sets the field represented by this Field object on the specified object argument to the specified new value. setBoolean(Object obj, boolean z) Sets the value of a field as a boolean on the specified object. setByte(Object obj, byte b) Sets the value of a field as a byte on the specified object. setChar(Object obj, char c) Sets the value of a field as a char on the specified object. setDouble(Object obj, double d) Sets the value of a field as a double on the specified object. setFloat(Object obj, float f) Sets the value of a field as a float on the specified object. setInt(Object obj, int i) Sets the value of a field as an int on the specified object. setLong(Object obj, long l) Sets the value of a field as a long on the specified object. setShort(Object obj, short s) Sets the value of a field as a short on the specified object. toString() Returns a string describing this Field.
22
Класс Class Field getField(String name) Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object. Field[] getFields() Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.
23
I: 99 import java.lang.reflect.*; import java.awt.*; class A {
public int i, j; i = 55; j = 66; } class SampleGet { public static void main(String[] args)throws Exception { A r = new A(); Class c = r.getClass(); Field f; Integer value; f = c.getField("i"); f.set(r, new Integer(99)); value = (Integer) f.get(r); System.out.println("I: " + value.toString()); I: 99
24
java.awt.Component import java.lang.reflect.*; import java.awt.*;
class SampleField { public static void main(String[] args) { Button g = new Button("aaaaa"); printFieldNames(g); } static void printFieldNames(Object o) { Class c = o.getClass(); Field[] publicFields = c.getFields(); for (int i = 0; i < publicFields.length; i++) { String fieldName = publicFields[i].getName(); Class typeClass = publicFields[i].getType(); String fieldType = typeClass.getName(); System.out.println("Name: " + fieldName + ", Type: " + fieldType); System.out.println("************* "); Class s = c.getSuperclass(); publicFields = s.getFields(); Name: TOP_ALIGNMENT, Type: float Name: CENTER_ALIGNMENT, Type: float Name: BOTTOM_ALIGNMENT, Type: float Name: LEFT_ALIGNMENT, Type: float Name: RIGHT_ALIGNMENT, Type: float Name: WIDTH, Type: int Name: HEIGHT, Type: int Name: PROPERTIES, Type: int Name: SOMEBITS, Type: int Name: FRAMEBITS, Type: int Name: ALLBITS, Type: int Name: ERROR, Type: int Name: ABORT, Type: int ************* java.awt.Component
25
original: java.awt.Rectangle[x=0,y=0,width=100,height=20]
import java.lang.reflect.*; import java.awt.*; class SampleSet { public static void main(String[] args) { Rectangle r = new Rectangle(100, 20); System.out.println("original: " + r.toString()); modifyWidth(r, new Integer(300)); System.out.println("modified: " + r.toString()); } static void modifyWidth(Rectangle r, Integer widthParam ) { Field widthField; Integer widthValue; Class c = r.getClass(); try { widthField = c.getField("width"); widthField.set(r, widthParam); } catch (NoSuchFieldException e) { System.out.println(e); } catch (IllegalAccessException e) { original: java.awt.Rectangle[x=0,y=0,width=100,height=20] modified: java.awt.Rectangle[x=0,y=0,width=300,height=20]
26
Выполнение методов Hello everybody. import java.lang.reflect.*;
class SampleInvoke { public static void main(String[] args) { String firstWord = "Hello "; String secondWord = "everybody."; String bothWords = append(firstWord, secondWord); System.out.println(bothWords); } public static String append(String firstWord, String secondWord) { String result = null; Class c = String.class; Class[] parameterTypes = new Class[] {String.class}; Method concatMethod; Object[] arguments = new Object[] {secondWord}; try { concatMethod = c.getMethod("concat", parameterTypes); result = (String) concatMethod.invoke(firstWord, arguments); } catch (NoSuchMethodException e) { System.out.println(e); } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { return result; Hello everybody.
27
Динамическое создание объектов
Использование конструктора без параметров Класс Class Object newInstance() Creates a new instance of the class represented by this Class object. Использование конструктора с параметрами Создать объект Class Создать объект Constructor, используя getConstructor() класса Class Использовать метод newInstance с параметром Object[] из класса Constructor
28
Использование конструктора без параметров
import java.lang.reflect.*; import java.awt.*; class SampleNoArg { public static void main(String[] args) { Rectangle r = (Rectangle) createObject("java.awt.Rectangle"); System.out.println(r.toString()); } static Object createObject(String className) { Object object = null; try { Class classDefinition = Class.forName(className); object = classDefinition.newInstance(); } catch (InstantiationException e) { System.out.println(e); } catch (IllegalAccessException e) { } catch (ClassNotFoundException e) { return object; } } java.awt.Rectangle[x=0,y=0,width=0,height=0]
29
Конструктор с параметрами
import java.lang.reflect.*; import java.awt.*; class SampleInstance { public static void main(String[] args) { Rectangle rectangle; Class rectangleDefinition; Class[] intArgsClass = new Class[] {int.class, int.class}; Integer height = new Integer(12); Integer width = new Integer(34); Object[] intArgs = new Object[] {height, width}; Constructor intArgsConstructor; try { rectangleDefinition = Class.forName("java.awt.Rectangle"); intArgsConstructor = rectangleDefinition.getConstructor(intArgsClass); rectangle = (Rectangle) createObject(intArgsConstructor, intArgs); } catch (Exception e) { System.out.println(e); } public static Object createObject(Constructor constructor, Object[] arguments) { System.out.println ("Constructor: " + constructor.toString()); Object object = null; object = constructor.newInstance(arguments); System.out.println ("Object: " + object.toString()); return object; 2 3 1 2 Constructor: public java.awt.Rectangle(int,int) Object: java.awt.Rectangle[x=0,y=0,width=12,height=34] 3
30
Определение массива class KeyPad { public boolean alive;
import java.lang.reflect.*; import java.awt.*; class SampleArray { public static void main(String[] args) { KeyPad target = new KeyPad(); printArrayNames(target); } static void printArrayNames(Object target) { Class targetClass = target.getClass(); Field[] publicFields = targetClass.getFields(); for (int i = 0; i < publicFields.length; i++) { String fieldName = publicFields[i].getName(); Class typeClass = publicFields[i].getType(); String fieldType = typeClass.getName(); if (typeClass.isArray()) { System.out.println("Name: " + fieldName + ", Type: " + fieldType); class KeyPad { public boolean alive; public Button power; public Button[] letters; public int[] codes; public TextField[] rows; public boolean[] states; } Name: letters, Type: [Ljava.awt.Button; Name: codes, Type: [I Name: rows, Type: [Ljava.awt.TextField; Name: states, Type: [Z
31
Определение типа компонентов массива
import java.lang.reflect.*; import java.awt.*; class SampleComponent { public static void main(String[] args) { int[] ints = new int[2]; Button[] buttons = new Button[6]; String[][] twoDim = new String[4][5]; printComponentType(ints); printComponentType(buttons); printComponentType(twoDim); } static void printComponentType(Object array) { Class arrayClass = array.getClass(); String arrayName = arrayClass.getName(); Class componentClass = arrayClass.getComponentType(); String componentName = componentClass.getName(); System.out.println("Array: " + arrayName + ", Component: " + componentName); Array: [I, Component: int Array: [Ljava.awt.Button;, Component: java.awt.Button Array: [[Ljava.lang.String;, Component: [Ljava.lang.String;
32
Значения элементов массива
import java.lang.reflect.*; class SampleGetArray { public static void main(String[] args) { int[] sourceInts = {12, 78}; int[] destInts = new int[2]; copyArray(sourceInts, destInts); String[] sourceStrgs = {"Hello ", "there ", "everybody"}; String[] destStrgs = new String[3]; copyArray(sourceStrgs, destStrgs); } public static void copyArray(Object source, Object dest) { for (int i = 0; i < Array.getLength(source); i++) { Array.set(dest, i, Array.get(source, i)); System.out.println(Array.get(dest, i)); 12 78 Hello there everybody
33
Класс Array static Object
get(Object array, int index) Returns the value of the indexed component in the specified array object. static boolean getBoolean(Object array, int index) Returns the value of the indexed component in the specified array object, as a boolean. static byte getByte(Object array, int index) Returns the value of the indexed component in the specified array object, as a byte. static char getChar(Object array, int index) Returns the value of the indexed component in the specified array object, as a char. static double getDouble(Object array, int index) Returns the value of the indexed component in the specified array object, as a double. static float getFloat(Object array, int index) Returns the value of the indexed component in the specified array object, as a float. static int getInt(Object array, int index) Returns the value of the indexed component in the specified array object, as an int. getLength(Object array) Returns the length of the specified array object, as an int. static long getLong(Object array, int index) Returns the value of the indexed component in the specified array object, as a long. static short getShort(Object array, int index) Returns the value of the indexed component in the specified array object, as a short
34
Класс Array static void
set(Object array, int index, Object value) Sets the value of the indexed component of the specified array object to the specified new value. setBoolean(Object array, int index, boolean z) Sets the value of the indexed component of the specified array object to the specified boolean value. setByte(Object array, int index, byte b) Sets the value of the indexed component of the specified array object to the specified byte value. setChar(Object array, int index, char c) Sets the value of the indexed component of the specified array object to the specified char value. setDouble(Object array, int index, double d) Sets the value of the indexed component of the specified array object to the specified double value. setFloat(Object array, int index, float f) Sets the value of the indexed component of the specified array object to the specified float value. setInt(Object array, int index, int i) Sets the value of the indexed component of the specified array object to the specified int value. setLong(Object array, int index, long l) Sets the value of the indexed component of the specified array object to the specified long value. setShort(Object array, int index, short s) Sets the value of the indexed component of the specified array object to the specified short value.
35
Класс Array static Object
newInstance(Class componentType, int length) Creates a new array with the specified component type and length. newInstance(Class componentType, int[] dimensions) Creates a new array with the specified component type and dimensions.
36
Создание массивов originalArray: 55 66 biggerArray:
import java.lang.reflect.*; class SampleCreateArray { public static void main(String[] args) { int[] originalArray = {55, 66}; int[] biggerArray = (int[]) doubleArray(originalArray); System.out.println("originalArray:"); for (int k = 0; k < Array.getLength(originalArray); k++) System.out.println(originalArray[k]); System.out.println("biggerArray:"); for (int k = 0; k < Array.getLength(biggerArray); k++) System.out.println(biggerArray[k]); } static Object doubleArray(Object source) { int sourceLength = Array.getLength(source); Class arrayClass = source.getClass(); Class componentClass = arrayClass.getComponentType(); Object result = Array.newInstance(componentClass, sourceLength * 2); System.arraycopy(source, 0, result, 0, sourceLength); return result; } } originalArray: 55 66 biggerArray:
37
Создание многомерных массивов
import java.lang.reflect.*; class SampleMultiArray { public static void main(String[] args) { // The oneDimA and oneDimB objects are one // dimensional int arrays with 5 elements. int[] dim1 = {5}; int[] oneDimA = (int[]) Array.newInstance(int.class, dim1); int[] oneDimB = (int[]) Array.newInstance(int.class, 5); // The twoDimStr object is a 5 X 10 array of String objects. int[] dimStr = {5, 10}; String[][] twoDimStr = (String[][]) Array.newInstance(String.class,dimStr); // The twoDimA object is an array of 12 int arrays. The tail // dimension is not defined. It is equivalent to the array // created as follows: // int[][] ints = new int[12][]; int[] dimA = {12}; int[][] twoDimA = (int[][]) Array.newInstance(int[].class, dimA); }
38
Класс - загрузчик Javac Do DemoLoader
public abstract class MyClassLoader { public void initialize() { } /** The work method. The cookie application will call you * here when it is time for you to start cooking. */ public void work() { /** The termination method. The cookie application will call you * here when it is time for you to stop cooking and shut down * in an orderly fashion. public void terminate() { public class Do { public static void main(String[] argv) { System.out.println(“Do"); MyClassLoader loader = null; String myClassName = argv[0]; try { Class lc = Class.forName(myClassName); Object myObject = lc.newInstance(); loader = (MyClassLoader)myObject; } catch (Exception e) { System.err.println("Error " + myClassName + e);} loader..initialize(); loader.work(); loader.terminate(); } public class DemoLoader extends MyClassLoader { public void work() { System.out.println(“Work."); } public void terminate() { System.out.println(“Terminate."); Javac Do DemoLoader
39
Тема самостоятельной работы
Написать загрузчик любых классов. В программе должны идентифицироваться все методы и поля загружаемого класса.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.