Delivering Excellence in Software Engineering ® 2006. EPAM Systems. All rights reserved. Reflection and Attributes.

Slides:



Advertisements
Similar presentations
Attributes Programming in C# Attributes CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Advertisements

Road Map Introduction to object oriented programming. Classes
C# Structs, operator overloading & attributes. Structs ~ Structures Structs are similar to classes: they represent data structures with data and functions.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
 2006 Pearson Education, Inc. All rights reserved Templates.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
.NET Attributes and Reflection “What a developer needs to know……” Dan Douglas Blog:
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
C# Tutorial From C++ to C#. Some useful links Msdn C# us/library/kx37x362.aspxhttp://msdn.microsoft.com/en- us/library/kx37x362.aspx.
C# vs. C++ What's Different & What's New. An example C# public sometype myfn { get; set; } C++ public: sometype myfn { sometype get (); void set (sometype.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Kalpesh Padia Reflection in.Net. OVERVIEW 9/19/
Reflection in.Net Siun-Wai Seow. Objective Explain.NET Reflection When to use it? How to use it? Topic is in the final exam.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Programming in C#. I. Introduction C# (or C-Sharp) is a programming language. C# is used to write software that runs on the.NET Framework. Although C#
All types in the CLR are self-describing – CLR provides a reader and writer for type definitions System.Reflection & System.Reflection.emit – You can ‘read’
Programming Languages and Paradigms Object-Oriented Programming.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
C#.Net Development Version 1.0. Overview Nullable Datatype Description ? HasValue Lifted Conversions null coalescing operator ?? Partial Classes Copyright.
Introduction to Building Windows 8.1 & Windows Phone Applications.
ABHISHEK BISWAS.NET Reflection Dynamically Create, Find and Invoke Types.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Modern Software Development Using C#.NET Chapter 5: More Advanced Class Construction.
Effective C# 50 Specific Way to Improve Your C# Item 42, 43.
Chapter 16 Applying UML and Patterns Craig Larman
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Introduction to C#. Why C#? Develop on the Following Platforms ASP.NET Native Windows Windows 8 / 8.1 Windows Phone WPF Android (Xamarin) iOS (Xamarin)
CSC241 Object-Oriented Programming (OOP) Lecture No. 4.
Reflection.NET Support for Reflection. What is Reflection Reflection: the process by which a program can observe and modify its own structure and behavior.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
Module 14: Attributes. Overview Overview of Attributes Defining Custom Attributes Retrieving Attribute Values.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Object Oriented Programming
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
Attributes C#.Net Software Development Version 1.0.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
More on Objects Mehdi Einali Advanced Programming in Java 1.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Peyman Dodangeh Sharif University of Technology Spring 2014.
Special Features of C# : Delegates, Events and Attributes.
Delivering Excellence in Software Engineering ® EPAM Systems. All rights reserved. Configuration.
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
.Net Reflection Taipan Tamsare. Overview Reflection core concepts Exploring metadata Detail information Attributes Building Types at runtime.
METADATA IN.NET Presented By Sukumar Manduva. INTRODUCTION  What is Metadata ? Metadata is a binary information which contains the complete description.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 7 th Lecture Pavel Ježek
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
Modern Programming Tools And Techniques-I
Creating Your Own Classes
Static data members Constructors and Destructors
Inheritance Allows extension and reuse of existing code
Chapter 3: Using Methods, Classes, and Objects
Reflection SoftUni Team Technical Trainers C# OOP Advanced
Advanced .NET Programming I 7th Lecture
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
CS360 Windows Programming
Advanced Programming in Java
Chapter 3 The .NET Framework Class Library (FCL)
Advanced Programming in Java
.NET and .NET Core 10. Enabling Contracts Pan Wuming 2017.
CIS 199 Final Review.
Advanced .NET Programming I 8th Lecture
Presentation transcript:

Delivering Excellence in Software Engineering ® EPAM Systems. All rights reserved. Reflection and Attributes

® EPAM Systems. All rights reserved. Reflection The Common Language Runtime makes type information ubiquitous, accessible, and extensible –reflection allows anyone to see any type (barring security) –reflection information never optional - all things are knowable –type information extensible via custom attributes –enables CLR automation of numerous services serialization, remoting, windows/web forms, web services –enables numerous kinds of tool development documentation/code generation, automated testing, … –System.Reflection namespace root of library support

® EPAM Systems. All rights reserved. The role of reflection

® EPAM Systems. All rights reserved. public static void GenerateSQL(Object obj) { Type type = obj.GetType(); Console.Write("create table {0} (", type.Name); bool needsComma = false; foreach (FieldInfo field in type.GetFields()) { if (needsComma) Console.Write(", "); else needsComma = true; Console.Write("{0} {1}", field.Name, field.FieldType); } Console.WriteLine(")"); } Example: using reflection

® EPAM Systems. All rights reserved. System.Type System.Type is the focal point of reflection –all objects and values are instances of types –can discover type of object or value using GetType method –can reference type by symbolic name using C# typeof keyword –types are themselves instances of type System.Type –inheritance/compatibility relationships traversable through System.Type

® EPAM Systems. All rights reserved. Types and Type.GetType

® EPAM Systems. All rights reserved. System.Type

® EPAM Systems. All rights reserved. Using System.Type All facets of a type are available at runtime –each kind of member has a reflection class that represents it –most types derive from System.Runtime.MemberInfo –can look up members by kind or globally –support for overloading and case-insensitive names for script/VB –can see non-accessible members if security allows

® EPAM Systems. All rights reserved. Reflection and the CLR type system

® EPAM Systems. All rights reserved. The reflection object model

® EPAM Systems. All rights reserved. using System.Reflection; public static void ListAllMembers( string assemblyPath ) { Assembly assembly = Assembly.LoadFrom(assemblyPath); foreach( Type type in assembly.GetTypes() ) { foreach( MemberInfo member in type.GetMembers() ) { Console.WriteLine("{0}.{1}", type, member.Name); } Example: walking every element in an assembly

® EPAM Systems. All rights reserved. Late binding Types may be instantiated and/or members accessed in a late bound manner –instantiate type in memory, choosing constructor to call –read/write fields of an object –invoke methods –invoke property getters and setters –register/unregister for events Late bound access slower than compile-time resolution –trading off performance for flexibility/extensibility

® EPAM Systems. All rights reserved. CreateInstance CreateInstance is the late-bound equivalent to operator new –methods of Activator and Assembly classes –former used with fully-specified type names –latter convenient when explicitly loading assemblies Both… –allocate storage for new type instance –call specified constructor –return generic object reference When coupled with interface-based member access, provides flexibility and performance

® EPAM Systems. All rights reserved. interface ICowboy { void Draw(); } class Tex : ICowboy {... } class Woody : ICowboy {... } class App { static void Main() { Console.Write("Enter western type to use: "); string typeName = Console.ReadLine(); // Late-bound activation ICowboy cb = (ICowboy) Activator.CreateInstance(Type.GetType(typeName)); // Early-bound member access: cb.Draw(); } Example: using Activator.CreateInstance

® EPAM Systems. All rights reserved. Example: using Assembly.CreateInstance public interface ICowboy { void Draw(); } public class Tex : ICowboy {... } class PluggableApp { static void Main() { Console.Write("Enter assembly to load: "); Assembly asm = Assembly.LoadFrom(Console.ReadLine()); Console.Write("Enter concrete type name: "); string typeName = Console.ReadLine(); ICowboy cb = (ICowboy)asm.CreateInstance(typeName); cb.Draw(); } public class Woody : ICowboy {... } icowboy.dll (reference by everyone) tex.dll woody.dll PluggableApp.exe

® EPAM Systems. All rights reserved. class Tex : ICowboy { public Tex( string name, int NumGuns ) {... } class App { static void Main() { object[] args = { "Jesse James", 4 }; ICowboy cb = (ICowboy) Activator.CreateInstance(typeof(Tex), args); cb.Draw(); } Constructor arguments and CreateInstance

® EPAM Systems. All rights reserved. Late-bound member access MemberInfo derivatives enable late-bound member access –much slower than CreateInstance+interface-based call pattern –typically reserved for scenarios where performance isn’t a goal interactive forms designers (e.g.: Windows/Web Forms) automated testing harnesses custom scripting engines Usage model –acquire Type object for target type –lookup member of interest (field, property, event, method) –use MemberInfo to read/write/invoke member on target object

® EPAM Systems. All rights reserved. Late-bound member access System.Type Lookup Method Lookup Method Return Value Operations GetFieldFieldInfo GetValue, SetValue GetPropertyPropertyInfo GetValue, SetValue GetEventEventInfo AddEventHandler, RemoveEventHandler GetMethodMethodInfo Invoke // Call method: double Add( double, double ) double CallAdd( object target, double x, double y ) { Type type = target.GetType(); MethodInfo method = type.GetMethod("Add"); if( method != null ) { object[] args = { x, y }; object result = method.Invoke(target, args); return (double)result; } return(0); }

® EPAM Systems. All rights reserved. Extending type information CLR type information is extensible using custom attributes –allows user-defined aspects of a type to be visible via reflection –custom attributes are classes derived from System.Attribute –C# uses IDL-like syntax with [ ] prior to the definition of the target –can be comma-delimited or in independent [ ] blocks –attribute parameters passed by position or name –attributes can be applied to an assembly or module using special syntax –attributes discovered using IsDefined and GetCustomAttributes

® EPAM Systems. All rights reserved. [assembly: Author("Larry")] // Applies to assembly [ Author("Moe", "Hi") ] // Applies to MyClass class MyClass { // Attribute applies to method f: [ Author("Curly", ] void f() { Object obj = null; obj.ToString(); } Example: specifying an attribute

® EPAM Systems. All rights reserved. using System; public class AuthorAttribute : Attribute { public string Name; public string Comment; public string Contact = ""; public AuthorAttribute( string n, string c ) { Name = n; Comment = c; } public AuthorAttribute( string n ) : this(n, "") { } Example: defining a custom attribute

® EPAM Systems. All rights reserved. using System; using System.Reflection; void DocType( string asmName, string typeName ) { Type attrType = typeof(AuthorAttribute); Assembly asm = Assembly.LoadFrom(asmName); if( asm.IsDefined(attrType, false) ) { Console.WriteLine("Assembly has an author"); } object[] attrs = asm.GetCustomAttributes(attrType, false); foreach( AuthorAttribute author in attrs ) { Console.WriteLine("Name: " + author.Name); Console.WriteLine("Notes: " + author.Comment); Console.WriteLine("Contact info: " + author.Contact); } Example: retrieving custom attributes

® EPAM Systems. All rights reserved. Summary Type information is easily accessible and ubiquitous Type information allows you to do things at runtime Type information allows you to do things at development-time Type information is extensible via custom attributes

Delivering Excellence in Software Engineering ® EPAM Systems. All rights reserved. For more information, please contact: Uladzimir Tsikhon Software Engineering Manager, Belarus Recourse Development Department EPAM Systems, Inc. Belarus, Minsk Phone: +375(17) ext 1756 Fax: +375(17)