Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Рефлексия Макаревич Л. Г. Introspection и reflection Самоанализ и рефлексия (java.lang.Class, java.lang.reflect) Получение информации о методах, полях классов, динамическое создание объектов и классов Основные возможности рефлексии Определить тип объекта Получить данные о методах, полях, конструкторах, родительском типе, модификаторах Выделить методы и константы интерфейса Создать объекты заранее неизвестного типа Получить.установить значения полей Вызвать метод Создать массив объектов неизвестного типа, изменять значения элементов Использование 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 } } Получение имени класса По ссылке на объект 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); 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(); class C int try { System.out.println(Class.forName("C")); int Class c1 = int.class; System.out.println(c1); System.out.println(c1.getName()); c1= Integer.class; System.out.println(c1.getName()); c1 = Integer.TYPE; System.out.println(c1.getName()); System.out.println(int.class.getName()); }catch(Exception e){} String s = new String(); Class c = m.getClass(); Class sc = c.getSuperclass(); } } java.lang.Integer int int Определение интерфейсов класса 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. 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 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 Модификаторы класса Class Modifier static boolean static boolean static boolean static boolean static boolean static boolean static boolean static boolean 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. static boolean isSynchronized(int mod) Return true if the integer argument includes the synchronized modifer, false otherwise. static boolean isTransient(int mod) Return true if the integer argument includes the transient modifer, false otherwise. static boolean isVolatile(int mod) Return true if the integer argument includes the volatile modifer, false otherwise. toString(int mod) static String Return a string describing the access modifier flags in the specified modifier. static int ABSTRACT The int value representing the abstract modifier. static int FINAL The int value representing the final modifier. static int INTERFACE The int value representing the interface modifier. static int NATIVE The int value representing the native modifier. static int PRIVATE The int value representing the private modifier. static int PROTECTED The int value representing the protected modifier. static int PUBLIC The int value representing the public modifier. static int STATIC The int value representing the static modifier. static int STRICT The int value representing the strictfp modifier. static int SYNCHRONIZED The int value representing the synchronized modifier. static int TRANSIENT The int value representing the transient modifier. static int VOLATILE The int value representing the volatile modifier. Класс Class int getModifiers() Returns the Java language modifiers for this class or interface, encoded in an integer. import java.lang.reflect.*; class My {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) { class My String className = sc.getName(); public System.out.println(className); final 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"); } } java.lang.Object Конструкторы boole an equals(Object obj) Class getDeclaringClass() Class Constructor Compares this Constructor against the specified object. Returns the Class object representing the class that declares the constructor represented by this Constructor object. Class [] int 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. 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. Class [] int 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. Objec t newInstance(Object[] initargs) String toString() 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. Returns a string describing this Constructor Класс Class Const getConstructor(Class[] parameterTypes) Returns a Constructor object that reflects the specified public constructor of the ructor class represented by this Class object. Const getConstructors() ructor[] 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. Const getDeclaredConstructor(Class[] parameterTypes) Returns a Constructor object that reflects the specified constructor of the class ructor or interface represented by this Class object. Const getDeclaredConstructors() Returns an array of Constructor objects reflecting all the constructors declared ructor[] by the class represented by this Class object. 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(); ( java.awt.Point java.awt.Dimension ) Constructor[] theConstructors = c.getConstructors(); () for (int i = 0; i < theConstructors.length; i++) { ( java.awt.Rectangle ) System.out.print("( "); ( int int int int ) 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(")"); } } } ( int int ) ( java.awt.Point ) ( java.awt.Dimension ) Класс Method boole an equals(Object obj) Class getDeclaringClass() Compares this Method against the specified object. Returns the Class object representing the class or interface that declares the method represented by this Method object. Class[ ] int 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. 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. Class[ ] getParameterTypes() Class getReturnType() Returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by this Method object. Returns a Class object that represents the formal return type of the method represented by this Method object. int hashCode() Returns a hashcode for this Method. Objec t invoke(Object obj, Object[] args) String toString() Invokes the underlying method represented by this Method object, on the specified object with the specified parameters. Returns a string describing this Method. Класс 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[ ] Method getDeclaredMethods() Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object. 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. 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 Parameter Types: Name: wait Return Type: void Parameter Types: long int Name: wait Return Type: void Parameter Types: Name: wait Return Type: void Parameter Types: long Name: equals Return Type: boolean Parameter Types: java.lang.Object Name: toString Return Type: java.lang.String Parameter Types: Name: notify Return Type: void Parameter Types: Name: notifyAll Return Type: void Parameter Types: Класс Field boole an Object equals(Object obj) Compares this Field against the specified object. get(Object obj) Returns the value of the field represented by this Field, on the specified object. boole an byte getBoolean(Object obj) Gets the value of a static or instance boolean field. 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. doubl e float 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. 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 int long 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. 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. Strin g getName() short getShort(Object obj) Clas s getType() int Returns the name of the field represented by this Field object. 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. 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) void setBoolean(Object obj, boolean z) void setByte(Object obj, byte b) void setChar(Object obj, char c) void setDouble(Object obj, double d) void setFloat(Object obj, float f) void setInt(Object obj, int i) void setLong(Object obj, long l) void setShort(Object obj, short s) Strin g toString() Sets the field represented by this Field object on the specified object argument to the specified new value. Sets the value of a field as a boolean on the specified object. Sets the value of a field as a byte on the specified object. Sets the value of a field as a char on the specified object. Sets the value of a field as a double on the specified object. Sets the value of a field as a float on the specified object. Sets the value of a field as an int on the specified object. Sets the value of a field as a long on the specified object. Sets the value of a field as a short on the specified object. Returns a string describing this Field. Класс 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. 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)); f = c.getField("i"); value = (Integer) f.get(r); System.out.println("I: " + value.toString()); } } I: 99 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); } java.awt.Component System.out.println("************* "); Class s = c.getSuperclass(); publicFields = s.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); } } } 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 ************* 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 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) { System.out.println(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] 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) { System.out.println(e); } catch (InvocationTargetException e) { System.out.println(e); } return result; } } Hello everybody. Динамическое создание объектов Использование конструктора без параметров Класс Class Object newInstance() Creates a new instance of the class represented by this Class object. Использование конструктора с параметрами Создать объект Class Создать объект Constructor, используя getConstructor() класса Class Использовать метод newInstance с параметром Object[] из класса Constructor Использование конструктора без параметров 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()); } java.awt.Rectangle[x=0,y=0,width=0,height= static Object createObject(String className) { 0] Object object = null; try { Class classDefinition = Class.forName(className); object = classDefinition.newInstance(); } catch (InstantiationException e) { System.out.println(e); } catch (IllegalAccessException e) { System.out.println(e); } catch (ClassNotFoundException e) { System.out.println(e); } return object; } } Конструктор с параметрами 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}; 2 Integer height = new Integer(12); Integer width = new Integer(34); Object[] intArgs = new Object[] {height, width}; 3 Constructor intArgsConstructor; try { rectangleDefinition = Class.forName("java.awt.Rectangle"); intArgsConstructor = rectangleDefinition.getConstructor(intArgsClass); 2 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; try { 3 object = constructor.newInstance(arguments); System.out.println ("Object: " + object.toString()); } catch (Exception e) { System.out.println(e); } return object; } } 1 Constructor: public java.awt.Rectangle(int,int) Object: java.awt.Rectangle[x=0,y=0,width=12,height=34] Определение массива import java.lang.reflect.*; import java.awt.*; class SampleArray { class KeyPad { public static void main(String[] args) { KeyPad target = new KeyPad(); public boolean alive; printArrayNames(target); public Button power; } public Button[] letters; static void printArrayNames(Object target) { public int[] codes; Class targetClass = target.getClass(); public TextField[] rows; Field[] publicFields = targetClass.getFields(); public boolean[] states; 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); } } } } Name: letters, Type: [Ljava.awt.Button; Name: codes, Type: [I Name: rows, Type: [Ljava.awt.TextField; Name: states, Type: [Z Определение типа компонентов массива import java.lang.reflect.*; import java.awt.*; class SampleComponent { public static void main(String[] args) { int[] ints = new int[2]; Array: [I, Component: int Button[] buttons = new Button[6]; Array: [Ljava.awt.Button;, Component: java.awt.Button String[][] twoDim = new String[4][5]; printComponentType(ints); Array: [[Ljava.lang.String;, Component: [Ljava.lang.String; 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); } } Значения элементов массива import java.lang.reflect.*; class SampleGetArray { public static void main(String[] args) { int[] sourceInts = {12, 78}; int[] destInts = new int[2]; copyArray(sourceInts, destInts); 12 String[] sourceStrgs = {"Hello ", "there ", "everybody"}; 78 String[] destStrgs = new String[3]; copyArray(sourceStrgs, destStrgs); } Hello there 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)); } } } everybody Класс Array static Object get(Object array, int index) Returns the value of the indexed component in the specified array object. static boolea n static byte getBoolean(Object array, int index) Returns the value of the indexed component in the specified array object, as a boolean. 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. static 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 Класс 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. static void setBoolean(Object array, int index, boolean z) Sets the value of the indexed component of the specified array object to the specified boolean value. static void setByte(Object array, int index, byte b) Sets the value of the indexed component of the specified array object to the specified byte value. static void setChar(Object array, int index, char c) Sets the value of the indexed component of the specified array object to the specified char value. static void setDouble(Object array, int index, double d) Sets the value of the indexed component of the specified array object to the specified double value. static void setFloat(Object array, int index, float f) Sets the value of the indexed component of the specified array object to the specified float value. static void setInt(Object array, int index, int i) Sets the value of the indexed component of the specified array object to the specified int value. static void setLong(Object array, int index, long l) Sets the value of the indexed component of the specified array object to the specified long value. static void setShort(Object array, int index, short s) Sets the value of the indexed component of the specified array object to the specified short value. Класс Array static Objec newInstance(Class componentType, int length) t Creates a new array with the specified component type and length. static Objec newInstance(Class componentType, int[] dimensions) t Creates a new array with the specified component type and dimensions. Создание массивов import java.lang.reflect.*; class SampleCreateArray { public static void main(String[] args) { int[] originalArray = {55, 66}; int[] biggerArray = (int[]) doubleArray(originalArray); originalArray: System.out.println("originalArray:"); 55 for (int k = 0; k < Array.getLength(originalArray); k++) 66 System.out.println(originalArray[k]); System.out.println("biggerArray:"); for (int k = 0; k < Array.getLength(biggerArray); k++) System.out.println(biggerArray[k]); biggerArray: 55 66 } 0 static Object doubleArray(Object source) { 0 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; } } Создание многомерных массивов 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); } } Класс - загрузчик public abstract class MyClassLoader { public void initialize() { public class Do { } public static void main(String[] argv) { /** The work method. The cookie application will call you System.out.println(“Do"); * here when it is time for you to start cooking. MyClassLoader loader = null; */ String myClassName = argv[0]; public void work() { try { } Class lc = Class.forName(myClassName); /** The termination method. The cookie application will call you Object myObject = lc.newInstance(); * here when it is time for you to stop cooking and shut down loader = (MyClassLoader)myObject; * in an orderly fashion. } } catch (Exception e) { */ System.err.println("Error " + myClassName + e);} public void terminate() { loader..initialize(); } loader.work(); public class DemoLoader extends MyClassLoader { loader.terminate(); } public void work() { System.out.println(“Work."); } } public void terminate() { System.out.println(“Terminate."); } } Javac Do DemoLoader Тема самостоятельной работы Написать загрузчик любых классов. В программе должны идентифицироваться все методы и поля загружаемого класса.