Presentation is loading. Please wait.

Presentation is loading. Please wait.

Reflection SoftUni Team Technical Trainers C# OOP Advanced

Similar presentations


Presentation on theme: "Reflection SoftUni Team Technical Trainers C# OOP Advanced"— Presentation transcript:

1 Reflection SoftUni Team Technical Trainers C# OOP Advanced
Software University

2 Table of Contents What? Why? Where? Reflection API Type Class
* Table of Contents What? Why? Where? Reflection API Type Class Reflecting Fields Reflecting Constructors Reflecting Methods Reflecting Attributes (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

3 Questions sli.do #7573

4 What? Why? Where?

5 What is Metaprogramming?
Writing programs that treat other programs as their data Metaprogramming is the writing of computer programs with the ability to treat programs as their data. It means that a program could be designed to read, generate, analyze or transform other programs, and even modify itself while running. In some cases, this allows programmers to minimize the number of lines of code to express a solution (hence reducing development time), or it gives programs greater flexibility to efficiently handle new situations without recompilation. The language in which the metaprogram is written is called the metalanguage. The language of the programs that are manipulated is called the object language. Source: © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

6 The ability of a programming language to be its own metalanguage
What is Reflection? The ability of a programming language to be its own metalanguage reflection is the ability of a computer program to examine, introspect, and modify its own structure and behavior at runtime. source: © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

7 Code is easier to maintain and extend
Why Reflection? Code is easier to maintain and extend Reflection is quite powerful and can be very useful. For instance, when mapping objects to tables in a database at runtime or when mapping the statements in a script language to method calls on real objects at runtime. © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

8 Where is Reflection used?
Writing tools for programmers Reflection can be used for observing and modifying program execution at runtime. A reflection-oriented program component can monitor the execution of an enclosure of code and can modify itself according to a desired goal related to that enclosure. This is typically accomplished by dynamically assigning program code at runtime. In object-oriented programming languages such as Java and C#, reflection allows inspection of classes, interfaces, fields and methods at runtime without knowing the names of the interfaces, fields, methods at compile time. It also allows instantiation of new objects and invocation of methods. Reflection can be used to adapt a given program to different situations dynamically. Reflection-oriented programming almost always requires additional knowledge, framework, relational mapping, and object relevance in order to take advantage of more generic code execution. Reflection is often used as part of software testing, such as for the runtime creation/instantiation of mock objects. Reflection is also a key strategy for metaprogramming. In some object-oriented programming languages, such as C# and Java, reflection can be used to override member accessibility rules. For example, reflection makes it possible to change the value of a field marked "private" in a third-party library's class. © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

9 Reflection API

10 Primary way to access metadata
Type Class Primary way to access metadata Type is the root of the System.Reflection functionality and is the primary way to access metadata. Use the members of Type to get information about a type declaration, about the members of a type (such as the constructors, methods, fields, properties, and events of a class), as well as the module and the assembly in which the class is deployed. Type describes data types. It stores type information in a variable, property or field. The Type class represents the program's metadata, which is a description of its structure but not the instructions that are executed. © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

11 Type Class – How to obtain it?
Compile time: Type myType = typeof(ClassName); Before doing any inspection on a class you need to obtain its Type object. All classes in C# including the primitive types (int, long, float etc.) including arrays have an associated Type object. Run time: "Relevant" to what? Type myType = Type.GetType("Namespace.ClassName") © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

12 type.Name vs type.FullName
Name of a Type type.Name vs type.FullName From a Type object you can obtain its name in two versions. The fully qualified class name (including namespace name) is obtained using the property Name where as if you want the class name without the namespace name you can obtain it using the FullName property © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

13 Base Type of a Class and Interfaces
Type baseType = testClass.BaseType; Type[] interfaces = testClass.GetInterfaces(); The superclass class object is a Class object like any other, so you can continue doing class reflection on that too. A class can implement many interfaces. Therefore an array of Class is returned. Interfaces are also represented by Class objects in Java Reflection. NOTE: Only the interfaces specifically declared implemented by a given class is returned. If a superclass of the class implements an interface, but the class doesn't specifically state that it also implements that interface, that interface will not be returned in the array. Even if the class in practice implements that interface, because the superclass does. To get a complete list of the interfaces implemented by a given class you will have to consult both the class and its superclasses recursively. © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

14 New Instance Type sbType = Type.GetType("System.Text.StringBuilder");
StringBuilder sbInstance = (StringBuilder) Activator.CreateInstance(sbType); © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

15 Demo © Software University Foundation – http://softuni.org
This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

16 Obtaining Fields of an Class
FieldInfo[] publicFields = type.GetFields(); FieldInfo[] nonPublicFields = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo[] staticPublicFields = type.GetFields(BindingFlags.Static | BindingFlags.Public); © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

17 Useful when creating columns of the type in database tables
Field Type and Name FieldInfo field = type.GetField("fieldName"); string fieldName = field.Name; Type fieldType = field.FieldType; Useful when creating columns of the type in database tables © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

18 Field Altering Type testType = typeof(Test); Test testObj =
(Test) Activator.CreateInstance(testType); FieldInfo field = testType.GetField("testInt"); field.SetValue(testObj, 5); int fieldValue = (int) field.GetValue(testObj); WARNING: use with extreme caution as you could alter an objects internal state! © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

19 These properties helps to get modifier of a field
Modifiers field.IsPrivate //private field.IsPublic //public field.IsNonPublic //everything but public field.IsFamily //protected field.IsAssembly //internal etc… IsPrivate – check if field is These properties helps to get modifier of a field © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

20 Exercises in Class

21 Obtaining Constructors of an Object
ConstructorInfo[] publicCtors = type.GetConstructors(); ConstructorInfo[] nonPublicCtors = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic); ConstructorInfo[] staticPublicCtors = type.GetConstructors(BindingFlags.Static | BindingFlags.Public); © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

22 Obtaining a Certain Constructor
ConstructorInfo constructor = type.GetConstructor(Type[] parametersType); If you know the precise parameter types of the constructor you want to access, you can do so rather than obtain an array of all constructors. This example returns the public constructor of the given class. © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

23 Instantiating Objects
StringBuilder builder = (StringBuilder)constructor.Invoke(object[] params); The .Invoke method takes an array of objects and you must supply exactly one parameter per argument in the constructor you are invoking. In this case it was a constructor taking a string, so one string must be supplied. Supply an array of object parameters for each argument in the constructor you are invoking © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

24 Constructor Parameters
Type[] parameterTypes = constructor.GetParameters(); © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

25 Obtaining Methods of an Object
MethodInfo[] publicMethods = type.GetMethods(); MethodInfo[] nonPublicMethods = type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic); MethodInfo[] staticPublicMethods = type.GetMethods(BindingFlags.Static | BindingFlags.Public); © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

26 Obtaining а Certain Method of an Object
Type sbType = typeof(StringBuilder); Type[] methodArgumentsType = new Type[] { typeof(string) }; MethodInfo appendMethod = sbTyp.GetMethod("Append", methodArgumentsType); Types of arguments for that method if it has Method name © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

27 Invoking Methods object[] parameters = new object[] { "hi!" };
appendMethod.Invoke(builder, parameters); If the method is static you supply null instead of an object instance. In this example, if doSomething(String.class) is not static, you need to supply a valid MyObject instance instead of null. The invoke(Object target, Object ... parameters) method takes an optional amount of parameters, but you must supply exactly one parameter per argument in the method you are invoking. In this case it was a method taking a String, so one String must be supplied. Target object instance for which to invoke the method Parameters for the method © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

28 Method Parameters and Return Type
ParameterInfo[] appendParameters = appendMethod.GetParameters(); Type returnType = appendMethod.ReturnType; © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

29 Exercises in Class

30 Obtaining Attributes var attributes = type.GetCustomAttributes();
foreach(Attribute attribute in attributes) { //do something with attribute } © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

31 Obtaining Method/Field Attributes
var attributes = field/method.GetCustomAttributes(); foreach(Attribute attribute in attributes) { //do something with attribute } © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

32 Exercises in Class

33 Summary What are the: Benefits Drawbacks Of using reflection?
Main benefit: code becomes easy to extend and maintain because it adapts at runtime Main drawback: - performance is sacrificed

34 Reflection https://softuni.bg/csharp-advanced-oop
© Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

35 License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license "OOP" course by Telerik Academy under CC-BY-NC-SA license © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

36 Free Trainings @ Software University
Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software Facebook facebook.com/SoftwareUniversity Software YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.


Download ppt "Reflection SoftUni Team Technical Trainers C# OOP Advanced"

Similar presentations


Ads by Google