Скачать презентацию
Идет загрузка презентации. Пожалуйста, подождите
Презентация была опубликована 9 лет назад пользователемВалерий Родионов
1 © Luxoft Training 2013 Using Reflection API in Java
2 © Luxoft Training 2013 Introduction Reflection or introspection is the ability of a program to examine and modify its structure and behavior Programming paradigm in the foundation of reflection is called reflective programming Java Reflection API can view information about classes, interfaces, methods, fields, constructors, and annotations during Java program runtime. You dont need to know names of inspected elements to do that 7-2 What is Reflection
3 © Luxoft Training 2013 Class introspection By using reflection you can retrieve the following information about a class: Class name Access modifiers Package information Superclasses Implemented interfaces If you know the class name you can also load and instantiate it 7-3 Introduction
4 © Luxoft Training 2013 Class introspection Before you inspect the class, you need to get the java.lang.Class object that describes the class All java classes (including primitives and arrays) have associated java.lang.Class java.lang.Class can be retrieved in three ways: Class myObjectClass = myObject.getClass() Class myClass = MyClass.class If you know the class name you can also load it: 7-4 The Class object
5 © Luxoft Training 2013 Class introspection Full class name: Class name without package: 7-5 Getting class name
6 © Luxoft Training 2013 Class introspection Using you can get a bitmask that defines access modifiers of a class. Using the group of methods Modifiers.isAbstract(int modifiers), Modifiers.isFinal(int modifiers), Modifiers.isInterface(int modifiers) etc., you can check the byte mask and find the corresponding modifier 7-6 Getting class modifiers
7 © Luxoft Training 2013 Class introspection Package package = aClass.getPackage() The package object describes package information such as package name 7-7 Getting the information about package
8 © Luxoft Training 2013 Class introspection Class superclass = aClass.getSuperclass(); You can go up the hierarchy to the Object class. 7-8 Getting the superclass
9 © Luxoft Training 2013 Class introspection Class[] interfaces = aClass.getInterfaces(); If this object represents a class, the return value is an array containing objects representing all interfaces implemented by the class. The order of the interface objects in the array corresponds to the order of the interface names in the implements clause of the declaration of the class represented by this object. For example, given the declaration: class Shimmer implements FloorWax, DessertTopping {... } suppose the value of s is an instance of Shimmer; the value of the expression: s.getClass().getInterfaces()[0] is the Class object that represents interface FloorWax; the value of: s.getClass().getInterfaces()[1] is the Class object represents interface DessertTopping. 7-9 Getting the implemented interfaces
10 © Luxoft Training 2013 Class introspection Constructors, methods, fields, and annotations can be received using 7-10 Getting other class elements The Constructor, Method, Field, Annotation classes are used to describe corresponding elements
11 © Luxoft Training 2013 Creating New Class Instance The Class newInstance() class method creates a class instance that describes this Class This is similar to creating an object using the new statement and to calling a no-argument constructor: 7-11 Class.newInstance()
12 © Luxoft Training 2013 Creating New Class Instance May throw exceptions: IllegalAccessException when a class or its no-argument constructor are not available InstantiationException if Class object represents an abstract class, an interface, an array class, a primitive or void ExceptionInInitializerError if an error occurred in the static initializer SecurityException if a security violation to create a class instance takes place 7-12 Class.newInstance()
13 © Luxoft Training 2013 Introspection of class fields Class.getFields() Class c = obj.getClass(); Field[] publicFields = c.getFields(); for (Field field : publicFields) { Class fieldType = field.getType(); System.out.println(Name: " + field.getName()); System.out.println(Type: " + fieldType.getName()); } Class c = obj.getClass(); Field field = c.getField("name"); String nameValue = (String) field.get(obj); field.set(obj, "New name");
14 © Luxoft Training 2013 Class c = obj.getClass(); Method[] methods = c.getMethods(); for (Method method : methods) { System.out.println(Name: " + method.getName()); System.out.println(Returning type: " + method.getReturnType().getName()); Class[] paramTypes = method.getParameterTypes(); System.out.print(Parameter types: "); for (Class paramType : paramTypes) { System.out.print(" " + paramType.getName()); } System.out.println(); } Introspection of class methods Class.getMethods()
15 © Luxoft Training 2013 Class method invocation Method.invoke(obj,args) Class c = obj.getClass(); Class[] paramTypes = new Class[] { String.class, int.class }; Method method = c.getMethod( "getCalculateRating", paramTypes); Object[] args = new Object[] { new String("First Calculate"), new Integer(10) }; Double d = (Double) method.invoke(obj, args);
16 © Luxoft Training 2013Example 7-16 ClassSpyTutor
17 © Luxoft Training 2013Example 7-17 ReflectionTutor
Еще похожие презентации в нашем архиве:
© 2024 MyShared Inc.
All rights reserved.