Reflection SoftUni Team Technical Trainers C# OOP Advanced

Slides:



Advertisements
Similar presentations
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
Advertisements

Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Static Members Static Variables & Methods SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
Asynchronous Programming Writing Asynchronous Code in Java SoftUni Team Technical Trainers Software University
Strings and Text Processing
Version Control Systems
Static Members and Namespaces
Databases basics Course Introduction SoftUni Team Databases basics
Abstract Classes, Abstract Methods, Override Methods
Sets, Hash table, Dictionaries
C# Basic Syntax, Visual Studio, Console Input / Output
Interface Segregation / Dependency Inversion
C# Basic Syntax, Visual Studio, Console Input / Output
Introduction to MVC SoftUni Team Introduction to MVC
PHP MVC Frameworks Course Introduction SoftUni Team Technical Trainers
Reflection SoftUni Team Technical Trainers Java OOP Advanced
Introduction to Entity Framework
ASP.NET Unit Testing Unit Testing Web API SoftUni Team ASP.NET
Classes, Properties, Constructors, Objects, Namespaces
Mocking tools for easier unit testing
State Management Cookies, Sessions SoftUni Team State Management
EF Code First (Advanced)
PHP MVC Frameworks MVC Fundamentals SoftUni Team Technical Trainers
OOP Course - Virtual Trip
EF Relations Object Composition
Heaps and Priority Queues
Repeating Code Multiple Times
Inheritance Class Hierarchies SoftUni Team Technical Trainers C# OOP
Java OOP Overview Classes and Objects, Members and Class Definition, Access Modifier, Encapsulation Java OOP Overview SoftUni Team Technical Trainers.
Basic Tree Data Structures
Abstraction, Interface, Inheritance, Polymorphism, Override / Overload
Balancing Binary Search Trees, Rotations
Debugging and Troubleshooting Code
Entity Framework: Relations
Fast String Manipulation
Functional Programming
The Right Way Control Flow
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
MVC Architecture, Symfony Framework for PHP Web Apps
Regular Expressions (RegEx)
C# Advanced Course Introduction SoftUni Team C# Technical Trainers
Databases Advanced Course Introduction SoftUni Team Databases Advanced
Best practices and architecture
Arrays and Multidimensional Arrays
Data Definition and Data Types
Multidimensional Arrays, Sets, Dictionaries
Extending functionality using Collections
Functional Programming
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
C# Advanced Course Introduction SoftUni Team C# Technical Trainers
Exporting and Importing Data
Introduction to TypeScript & Angular
Train the Trainers Course
Iterators and Comparators
Reflection SoftUni Team Technical Trainers C# OOP Advanced
Hibernate (JPA) Code First Entity Relations
Spring Data Advanced Querying
Inheritance and Prototypes
Version Control Systems
Polymorphism, Interfaces, Abstract Classes
/^Hel{2}o\s*World\n$/
Files, Directories, Exceptions
JavaScript: ExpressJS Overview
Iterators and Generators
What is Encapsulation, Benefits, Implementation in Java
Multidimensional Arrays
Presentation transcript:

Reflection SoftUni Team Technical Trainers C# OOP Advanced Software University http://softuni.bg

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

Questions sli.do #CSharp-OOP

Reflection What? Why? Where? When?

What is Metaprogramming? Programming technique in which computer programs have the ability to treat other programs as their data Programs can be designed to: Read Generate Analyze Transform Modify itself while running.

What is Reflection? The ability of a programming language to be it’s own metalanguage Programs can examine information about itself

Why, Where Reflection? Code becomes more extendible Reduces code length significantly Easier maintenance Testing Tools for programmers

When Reflection? If it is possible to perform an operation without using reflection, then it is preferable to avoid using it Cons from using Reflection Performance overhead Security restrictions Exposure of internals

Reflecting Class and Members Reflection API Reflecting Class and Members

You need fully qualified class name as string Type Class Primary way to access metadata Obtain at compile time if you know it’s name Obtain at run time if the name is unknown Type myType = typeof(ClassName); 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. Type myType = Type.GetType("Namespace.ClassName") You need fully qualified class name as string © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Class Name Obtain Class name Fully qualified class name - Type.FullName Class name without the package name - Type.Name string fullName = typeOf(SomeClass).FullName; string simpleName = typeOf(SomeClass).Name; © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Base Class and Interfaces Obtain base class Obtain interfaces Only the interfaces specifically declared implemented by a given class are returned Type baseType = testClass.BaseType; Type[] interfaces = testClass.GetInterfaces(); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

New Instance CreateInstance - creates an instance of a type by invoking the constructor that best matches the specified arguments Type sbType = Type.GetType("System.Text.StringBuilder"); StringBuilder sbInstance = (StringBuilder) Activator.CreateInstance(sbType); StringBuilder sbInstCapacity = (StringBuilder)Activator .CreateInstance(sbType, new object[] {10}); https://msdn.microsoft.com/en-us/library/wccyzw83(v=vs.110).aspx © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Reflect Fields Obtain public fields Obtain all fields FieldInfo field = type.GetField("name"); FieldInfo[] publicFields = type.GetFields(); FieldInfo[] allFields = type.GetFields( BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Field Type and Name Get field name and type FieldInfo field = type.GetField("fieldName"); string fieldName = field.Name; Type fieldType = field.FieldType; © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

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

Access Modifiers Each modifier is a flag bit that is either set or cleared Check access modifier of a member of the class field.IsPrivate //private field.IsPublic //public field.IsNonPublic //everything but public field.IsFamily //protected field.IsAssembly //internal etc… IsPrivate – check if field is © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Reflect Constructors Obtain constructors Obtain all non static constructors ConstructorInfo[] publicCtors = type.GetConstructors(); ConstructorInfo[] allNonStaticCtors = type.GetConstructors( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Reflect Constructors(2) Obtain a certain constructor Get parameters type ConstructorInfo constructor = type.GetConstructor(new Type[] parametersType); Type[] parameterTypes = constructor.GetParameters(); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Instantiating Objects Instantiating objects using constructor StringBuilder builder = (StringBuilder)constructor.Invoke(new object[] params); Supply an array of object parameters for each argument in the constructor you are invoking 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. © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Reflect Methods Obtain public methods Obtain certain method MethodInfo[] publicMethods = sbType.GetMethods(); MethodInfo appendMethod = sbType.GetMethod("Append"); MethodInfo overloadMethod = sbType.GetMethod( "Append", new []{typeof(string)}); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Method Invoke Obtain method parameters and return type Invoke methods ParameterInfo[] appendParameters = appendMethod.GetParameters(); Type returnType = appendMethod.ReturnType; Parameters for the method appendMethod.Invoke( builder, new object[] { "hi!“ }); Target object instance © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Live Exercises in Class (Lab) Reflection Live Exercises in Class (Lab) © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

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

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

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

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