SlideShare una empresa de Scribd logo
1 de 40
Descargar para leer sin conexión
Metaprograms
and
metadata
Prof. Dr. Ralf Lämmel
Universität Koblenz-Landau
Software Languages Team
Motivation
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Elevator speech
So programs are programs and data is data.
Or perhaps programs could be data?
Or rather data could be programs?
What if programs process data representing programs?
Those are metaprograms.
(Reflection is an important way of doing metaprogramming.)
What if data represents data about programs?
This is metadata.
Programming is for kids.
Metaprogramming is for men nerds.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Metaprogramming terminology
• A metaprogram is a program that manipulates other
programs. That is, programs correspond to data of
metaprograms.
• 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.
• The ability of a programming language to be its own
metalanguage is called reflection . If reflection is limited to
“read access”, then this is called introspection.
• Reflection can be achieved in very different ways:
– API-based access to program (Java).
– Special language and compiler support (C++ templates).
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Examples of metaprograms
• A Java program that pretty prints arithmetic expressions.
• … evaluates them.
• … transforms them (e.g., optimizes them).
• A Java compiler because:
– it inspects Java code, and
– it produces byte code.
• If the Java compiler is written in Java, it is a reflective
meta-program; if it is written in Haskell instead, it is just a
meta-program.
• A byte-code engineering program because it analyses,
generates, or transforms programs in JVM byte code.
• …
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Scenario
• Create an object through reflection API
• Invoke a method through reflection API
Why is this interesting?
• Imagine the class or the method are not known until runtime.
The “Hello World” of java.lang.reflect
DEMO
See package helloworld of
https://github.com/101companies/101repo/tree/master/
technologies/Java_platform/samples/javaReflectionSamples
Reflection
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Java’s “built-in” reflection
Basics (Covered today)
• java.lang.Class
• java.lang.reflect.Field
• java.lang.reflect.Method
• java.lang.reflect.Constructor
Advanced (Optional material included)
• java.lang.reflect.Proxy
Object model for
object models
Deep support for
dynamic classes and
the proxy design
pattern
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
java.lang.Class
• Represents classes (and interfaces) in a Java app.
• Each object knows of its class: obj.getClass()
• Each class knows of its class: String.class
• Primitive types have an associated class.
• Even void has an associated class.
• Class cannot be regularly instantiated.
• Instead the class loader uses defineClass:
– Input: byte code
– Output: an instance of type Class
To treat
argument and
result types
homogeneously
and precisely
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
java.lang.Class
interface
• Map strings to class objects (forName)
• Getter
– Name
– Constructors
– Fields
– Methods
– Interfaces
– Annotations
– Package
– Superclass
– Enclosing class
• NO SETTERS
• Various other inspectors (“tests”)
• Instantiation (but see constructors)
• Cast operations
• …
This is one
manifestation of
Java’s reflection to
focus on
introspection.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
java.lang.reflect.Method
• Represents methods
– … of classes and interfaces
– static, initialization, instance, and abstract methods
• Constructors are treated very similar; see:
– java.lang.reflect.Constructor
• Does not provide byte-code access.
• Returned by getters on java.lang.Class.
• NO METHOD BODIES
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
java.lang.reflect.Method
interface
• Getters
– Name
– Parameter types
– Return type
– Type parameters
– Class
– Modifiers
– Annotations
– Parameter annotations
– …
• Invocation
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
java.lang.reflect.Field
Provides information about fields.
Provides dynamic access to fields.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
java.lang.reflect.Field
interface
• Getters
–Name
–Value (for a given object)
–Modifiers
–Annotations
–…
• Setters
–Value (for a given object)
Reflection examples
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Scenario
• Given an object of an arbitrary type.
• Provide a deep dump on the state of the object.
• That is, go over the fields recursively.
An object dumper
DEMO
See package dumper of
https://github.com/101companies/101repo/tree/master/
technologies/Java_platform/samples/javaReflectionSamples
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Total and cut
with the help of reflection.
295
DEMO
http://101companies.org/wiki/
Contribution:javaReflection
Please note the conciseness of the code
compared to javaComposition, for example.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
A challenge for (Java) reflection
Given a class, what are the subclasses of it?
Alas, there is no such member on “Class”.
The set of classes known to the system is simply the
set of classes loaded so far. One could assume a scan
over the full classpath to get to know more classes,
but automatically loading all these classes is
expensive and may not be intended.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Find and load all classes of a package
297
DEMO
See package packagelist of
https://github.com/101companies/101repo/tree/master/
technologies/Java_platform/samples/javaReflectionSamples
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Find (and load) all classes in a given package.
The search relies on a directory listing.
public static Iterable<Class<?>> getClassesInPackage(Package p) {
LinkedList<Class<?>> l = new LinkedList<Class<?>>();
String name = p.getName();
name = name.replace('.',File.separatorChar);
File dir = new File(name);
if (!dir.exists())
throw new RuntimeException("Can't find package!");
for (String f : dir.list()) {
String classname = f.substring(0,f.length()-6);
try {
Class<?> clss = Class.forName(p.getName() + "." + classname);
l.add(clss);
}
catch (ClassNotFoundException e) {
// Ignore exception
}
}
return l;
}
Instead of using the
classpath, we assume a
translation of the package
name to the location in the
file system.
Metadata
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Metaprograms vs. metadata
Metaprograms are programs that generate, analyze, or
control other programs.
Metadata (generally) is data that is attached to programs or
other data to provide additional information (in particular,
application-specific information) for programs and data.
In Java, we can use annotations for metadata. It happens
that metaprograms often need annotations.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Sample annotation
@Test
	 public void testTotal() throws Exception {
	Document doc = DOMUtilities.loadDocument(sampleCompany);
	double total = total(doc);
	assertEquals(399747, total, 0);
	 }
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Annotations
Data associated with methods, fields, class, etc. that
does not affect the semantics of a program, but
controls metaprograms over the annotated object
programs.
Scenarios:
• Identify test methods and control execution (JUnit)
• Control serialization of objects as XML (JAXB)
• ... many other frameworks ...
.NET uses the term
“custom attributes”;
Java “adopted” them and
called them annotations
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Sample annotation
@RequestForEnhancement(
id = 2868724,
synopsis = "Enable time-travel",
engineer = "Mr. Peabody",
date = "4/1/3007"
)
Public void travelThroughTime(Date destination) { ...
}
“=“ notation can be
omitted if there is
only a single method
of name value.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Annotation declaration
for sample annotation
/**
* Describes a Request-For-Enhancement(RFE)
* for the API element at hand
*/
public @interface RequestForEnhancement {
int id();
String synopsis();
String engineer() default "[unassigned]";
String date(); default "[unimplemented]";
}
Thus, annotation declarations are
somewhat specific interface declarations.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Annotation rules
• An annotation decl takes the form of interface decl
except that …
– they start with an 'at' sign @;
– their method declarations must not have any parameters;
– … and must not have any throws clauses;
– their return types of the method must be one of the following:
• Primitive types;
• String;
• Class;
• Enum;
• Array types of the above types;
– there may be a default for each method.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Meta-annotations
aka Metametadata
• @Documented – controls whether or not the
declarations should be visible when targets are
documented in any way.
• @Inherited – controls whether or not a subclass (or a
member thereof) inherits the annotation when the
superclass (or a member thereof) was target.
• @Retention – (runtime, source, …) controls whether the
annotation will be available, accessible during runtime.
• @Target – (field, method, type, …, annotation) the kind of
declaration to which the annotation can be attached.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Scenario
• Take a class name as argument.
• Find all “test” methods in the class.
• Execute them.
• Keep a record of success and failure.
A tiny approximation of JUnit
307
DEMO
See package junitlight of
https://github.com/101companies/101repo/tree/master/
technologies/Java_platform/samples/javaReflectionSamples
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Summary
• Meta-programming comes in many forms:
– Analyze
– Transform
– Generate
– Compose
Code, where code is …
– Java source code, or
– JVM byte code.
• Meta-programming is used/needed all over the place:
– By the compiler
– By IDE and tool support (JUnit, …)
– By application generators
– By mapping tools (X/O/R)
– …
Programming is
for casual hackers;
meta-programming
is for real men
nerds.
More references.
FYI
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Extra meta-programming power
for Java
• BCEL, ASM, ... – Byte-code engineering libraries
• Javassist – Byte-code editing also at source level
• com.sun.source.tree – Compiler Tree API
• … various other technologies
Related topics: code generation and analysis
• “Code-Generation Techniques for Java”, article at OnJava.com
• “Generate Java Code”, article at codefutures.com
• “Source Code Analysis Using Java 6 APIs", article Java.net
References - FYI
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Further reading: Beyond Java
July 1991
7 x 9, 348 pp., 9 illus.
$45.00/£29.95 (PAPER)
Short
ISBN-10:
0-262-61074-4
ISBN-13:
978-0-262-61074-2
References - FYI
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Seminal references
• Brian C. Smith. Reflection and semantics in lisp. In Conference Record
of the Eleventh Annual ACM Symposium on Principles of Programming
Languages, pages 23--35. ACM Press, January 1984.
• Daniel P. Friedman and Mitchell Wand. Reification: Reflection without
metaphysics. In Conference Record of the 1984 ACM Symposium on
LISP and Functional Programming, pages 348--355, Austin, Texas,
August 1984. ACM Press.
• Mitchell Wand and Daniel P. Friedman. The mystery of the tower
revealed: A non-reflective description of the reflective tower. Lisp and
Symbolic Computation, 1(1):11--38, June 1988.
• Stanley Jefferson and Daniel P. Friedman. A simple reflective
interpreter. Lisp and Symbolic Computation, 9(2/3):181--202, May/June
1996.
References - FYI
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Online resources on Java reflection
Series at IBM developerWorks
• Part 1: Classes and class loading
• Part 2: Introducing reflection
• Part 3: Applied reflection
• Part 4: Class transformation with Javassist
• Part 5: Transforming classes on-the-fly
• Part 6: Aspect-oriented changes with Javassist
• Part 7: Bytecode engineering with BCEL
• Part 8: Replacing reflection with code generation
Miscellaneous
• Another simple reflection tutorial
• “Reflection API Code Samples”, samples @ SDN
• More on class loading:
– “Inside Class Loaders”, article at OnJava.com
– “Create a custom Java 1.2-style ClassLoader”, article at JavaWorld.com
References - FYI
Reflective proxies
Optional; beware:
advanced example.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Reflection-based proxies
Remember the Proxy Pattern?
Optional; beware:
advanced example.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Scenario
• Taken an object of any type.
• Return a proxy for that object.
• Forward all methods from proxy to real subject.
• In addition, produce tracing information.
A tracer proxy for any given object
DEMO Optional; beware:
advanced example.
See package tracer of
https://github.com/101companies/101repo/tree/master/
technologies/Java_platform/samples/javaReflectionSamples
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
java.lang.reflect.Proxy
• Proxy provides static methods for creating dynamic proxy
classes and instances, and it is also the superclass of all
dynamic proxy classes created by those methods.
• A (dynamic) proxy class is a class that implements a list of
interfaces specified at runtime when the class is created.
• A proxy interface is such an interface that is implemented by a
proxy class.
• A proxy instance is an instance of a proxy class. Each proxy
instance has an associated invocation handler object, which
implements the interface InvocationHandler. A method
invocation on a proxy instance through one of its proxy
interfaces will be dispatched to the invoke method of the
instance's invocation handler.
Optional; beware:
advanced example.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
java.lang.reflect.Proxy
If XYZ is an interface passed as an argument in the
creation of the proxy class, and obj is an instance of
the proxy class, then the following operations are
valid:
• obj instanceof XYZ
• (XYZ) obj
Optional; beware:
advanced example.

Más contenido relacionado

La actualidad más candente

STATICMOCK : A Mock Object Framework for Compiled Languages
STATICMOCK : A Mock Object Framework for Compiled Languages STATICMOCK : A Mock Object Framework for Compiled Languages
STATICMOCK : A Mock Object Framework for Compiled Languages ijseajournal
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
 
A Portable Approach for Bidirectional Integration between a Logic and a Stati...
A Portable Approach for Bidirectional Integration between a Logic and a Stati...A Portable Approach for Bidirectional Integration between a Logic and a Stati...
A Portable Approach for Bidirectional Integration between a Logic and a Stati...Sergio Castro
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8Raffi Khatchadourian
 
型ヒントについて考えよう!
型ヒントについて考えよう!型ヒントについて考えよう!
型ヒントについて考えよう!Yusuke Miyazaki
 
Python: The Programmer's Lingua Franca
Python: The Programmer's Lingua FrancaPython: The Programmer's Lingua Franca
Python: The Programmer's Lingua FrancaActiveState
 
A First Analysis of String APIs: the Case of Pharo
A First Analysis of String APIs: the Case of PharoA First Analysis of String APIs: the Case of Pharo
A First Analysis of String APIs: the Case of PharoESUG
 
Chapter1pp
Chapter1ppChapter1pp
Chapter1ppJ. C.
 
Realization of natural language interfaces using
Realization of natural language interfaces usingRealization of natural language interfaces using
Realization of natural language interfaces usingunyil96
 
Thesis+of+laleh+eshkevari.ppt
Thesis+of+laleh+eshkevari.pptThesis+of+laleh+eshkevari.ppt
Thesis+of+laleh+eshkevari.pptPtidej Team
 
A Taxonomy for Program Metamodels in Program Reverse Engineering
A Taxonomy for Program Metamodels in Program Reverse EngineeringA Taxonomy for Program Metamodels in Program Reverse Engineering
A Taxonomy for Program Metamodels in Program Reverse EngineeringHironori Washizaki
 
C++ to java
C++ to javaC++ to java
C++ to javaAjmal Ak
 
Domain specific languages and Scala
Domain specific languages and ScalaDomain specific languages and Scala
Domain specific languages and ScalaFilip Krikava
 
A Feature-Based Model for Nested Named-Entity Recognition at VLSP-2018 NER Ev...
A Feature-Based Model for Nested Named-Entity Recognition at VLSP-2018 NER Ev...A Feature-Based Model for Nested Named-Entity Recognition at VLSP-2018 NER Ev...
A Feature-Based Model for Nested Named-Entity Recognition at VLSP-2018 NER Ev...Minh Pham
 
Model-Driven Software Development - Language Workbenches & Syntax Definition
Model-Driven Software Development - Language Workbenches & Syntax DefinitionModel-Driven Software Development - Language Workbenches & Syntax Definition
Model-Driven Software Development - Language Workbenches & Syntax DefinitionEelco Visser
 

La actualidad más candente (18)

STATICMOCK : A Mock Object Framework for Compiled Languages
STATICMOCK : A Mock Object Framework for Compiled Languages STATICMOCK : A Mock Object Framework for Compiled Languages
STATICMOCK : A Mock Object Framework for Compiled Languages
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
 
A Portable Approach for Bidirectional Integration between a Logic and a Stati...
A Portable Approach for Bidirectional Integration between a Logic and a Stati...A Portable Approach for Bidirectional Integration between a Logic and a Stati...
A Portable Approach for Bidirectional Integration between a Logic and a Stati...
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
型ヒントについて考えよう!
型ヒントについて考えよう!型ヒントについて考えよう!
型ヒントについて考えよう!
 
Python: The Programmer's Lingua Franca
Python: The Programmer's Lingua FrancaPython: The Programmer's Lingua Franca
Python: The Programmer's Lingua Franca
 
A First Analysis of String APIs: the Case of Pharo
A First Analysis of String APIs: the Case of PharoA First Analysis of String APIs: the Case of Pharo
A First Analysis of String APIs: the Case of Pharo
 
Chapter1pp
Chapter1ppChapter1pp
Chapter1pp
 
Realization of natural language interfaces using
Realization of natural language interfaces usingRealization of natural language interfaces using
Realization of natural language interfaces using
 
Icsme16.ppt
Icsme16.pptIcsme16.ppt
Icsme16.ppt
 
Thesis+of+laleh+eshkevari.ppt
Thesis+of+laleh+eshkevari.pptThesis+of+laleh+eshkevari.ppt
Thesis+of+laleh+eshkevari.ppt
 
A Taxonomy for Program Metamodels in Program Reverse Engineering
A Taxonomy for Program Metamodels in Program Reverse EngineeringA Taxonomy for Program Metamodels in Program Reverse Engineering
A Taxonomy for Program Metamodels in Program Reverse Engineering
 
C++ to java
C++ to javaC++ to java
C++ to java
 
Icpc11c.ppt
Icpc11c.pptIcpc11c.ppt
Icpc11c.ppt
 
Domain specific languages and Scala
Domain specific languages and ScalaDomain specific languages and Scala
Domain specific languages and Scala
 
A Feature-Based Model for Nested Named-Entity Recognition at VLSP-2018 NER Ev...
A Feature-Based Model for Nested Named-Entity Recognition at VLSP-2018 NER Ev...A Feature-Based Model for Nested Named-Entity Recognition at VLSP-2018 NER Ev...
A Feature-Based Model for Nested Named-Entity Recognition at VLSP-2018 NER Ev...
 
Msr17a.ppt
Msr17a.pptMsr17a.ppt
Msr17a.ppt
 
Model-Driven Software Development - Language Workbenches & Syntax Definition
Model-Driven Software Development - Language Workbenches & Syntax DefinitionModel-Driven Software Development - Language Workbenches & Syntax Definition
Model-Driven Software Development - Language Workbenches & Syntax Definition
 

Similar a Metaprograms and metadata (as part of the the PTT lecture)

Selected design patterns (as part of the the PTT lecture)
Selected design patterns (as part of the the PTT lecture)Selected design patterns (as part of the the PTT lecture)
Selected design patterns (as part of the the PTT lecture)Ralf Laemmel
 
Generative programming (mostly parser generation)
Generative programming (mostly parser generation)Generative programming (mostly parser generation)
Generative programming (mostly parser generation)Ralf Laemmel
 
Language processing patterns
Language processing patternsLanguage processing patterns
Language processing patternsRalf Laemmel
 
Aspect-oriented programming with AspectJ (as part of the the PTT lecture)
Aspect-oriented programming with AspectJ (as part of the the PTT lecture)Aspect-oriented programming with AspectJ (as part of the the PTT lecture)
Aspect-oriented programming with AspectJ (as part of the the PTT lecture)Ralf Laemmel
 
Remote method invocation (as part of the the PTT lecture)
Remote method invocation (as part of the the PTT lecture)Remote method invocation (as part of the the PTT lecture)
Remote method invocation (as part of the the PTT lecture)Ralf Laemmel
 
A Survey of Object Oriented Programming LanguagesMaya Hris.docx
A Survey of Object Oriented Programming LanguagesMaya Hris.docxA Survey of Object Oriented Programming LanguagesMaya Hris.docx
A Survey of Object Oriented Programming LanguagesMaya Hris.docxdaniahendric
 
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?Chuk-Munn Lee
 
Introduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallIntroduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallJohn Mulhall
 
Bringing It All Together: Mapping Continuing Resources Vocabularies for Linke...
Bringing It All Together: Mapping Continuing Resources Vocabularies for Linke...Bringing It All Together: Mapping Continuing Resources Vocabularies for Linke...
Bringing It All Together: Mapping Continuing Resources Vocabularies for Linke...NASIG
 
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisCompiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisEelco Visser
 
Database programming including O/R mapping (as part of the the PTT lecture)
Database programming including O/R mapping (as part of the the PTT lecture)Database programming including O/R mapping (as part of the the PTT lecture)
Database programming including O/R mapping (as part of the the PTT lecture)Ralf Laemmel
 
Java quick reference
Java quick referenceJava quick reference
Java quick referenceArthyR3
 
A Strong Object Recognition Using Lbp, Ltp And Rlbp
A Strong Object Recognition Using Lbp, Ltp And RlbpA Strong Object Recognition Using Lbp, Ltp And Rlbp
A Strong Object Recognition Using Lbp, Ltp And RlbpRikki Wright
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming LanguageYLTO
 
Sparklis exploration et interrogation de points d'accès sparql par interactio...
Sparklis exploration et interrogation de points d'accès sparql par interactio...Sparklis exploration et interrogation de points d'accès sparql par interactio...
Sparklis exploration et interrogation de points d'accès sparql par interactio...SemWebPro
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 

Similar a Metaprograms and metadata (as part of the the PTT lecture) (20)

Selected design patterns (as part of the the PTT lecture)
Selected design patterns (as part of the the PTT lecture)Selected design patterns (as part of the the PTT lecture)
Selected design patterns (as part of the the PTT lecture)
 
XML data binding
XML data bindingXML data binding
XML data binding
 
Generative programming (mostly parser generation)
Generative programming (mostly parser generation)Generative programming (mostly parser generation)
Generative programming (mostly parser generation)
 
Language processing patterns
Language processing patternsLanguage processing patterns
Language processing patterns
 
Aspect-oriented programming with AspectJ (as part of the the PTT lecture)
Aspect-oriented programming with AspectJ (as part of the the PTT lecture)Aspect-oriented programming with AspectJ (as part of the the PTT lecture)
Aspect-oriented programming with AspectJ (as part of the the PTT lecture)
 
Remote method invocation (as part of the the PTT lecture)
Remote method invocation (as part of the the PTT lecture)Remote method invocation (as part of the the PTT lecture)
Remote method invocation (as part of the the PTT lecture)
 
Presentation
PresentationPresentation
Presentation
 
A Survey of Object Oriented Programming LanguagesMaya Hris.docx
A Survey of Object Oriented Programming LanguagesMaya Hris.docxA Survey of Object Oriented Programming LanguagesMaya Hris.docx
A Survey of Object Oriented Programming LanguagesMaya Hris.docx
 
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
 
Introduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallIntroduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John Mulhall
 
Bringing It All Together: Mapping Continuing Resources Vocabularies for Linke...
Bringing It All Together: Mapping Continuing Resources Vocabularies for Linke...Bringing It All Together: Mapping Continuing Resources Vocabularies for Linke...
Bringing It All Together: Mapping Continuing Resources Vocabularies for Linke...
 
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisCompiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static Analysis
 
Database programming including O/R mapping (as part of the the PTT lecture)
Database programming including O/R mapping (as part of the the PTT lecture)Database programming including O/R mapping (as part of the the PTT lecture)
Database programming including O/R mapping (as part of the the PTT lecture)
 
Java quick reference
Java quick referenceJava quick reference
Java quick reference
 
master_thesis_greciano_v2
master_thesis_greciano_v2master_thesis_greciano_v2
master_thesis_greciano_v2
 
A Strong Object Recognition Using Lbp, Ltp And Rlbp
A Strong Object Recognition Using Lbp, Ltp And RlbpA Strong Object Recognition Using Lbp, Ltp And Rlbp
A Strong Object Recognition Using Lbp, Ltp And Rlbp
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming Language
 
Stay fresh
Stay freshStay fresh
Stay fresh
 
Sparklis exploration et interrogation de points d'accès sparql par interactio...
Sparklis exploration et interrogation de points d'accès sparql par interactio...Sparklis exploration et interrogation de points d'accès sparql par interactio...
Sparklis exploration et interrogation de points d'accès sparql par interactio...
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 

Más de Ralf Laemmel

Keynote at-icpc-2020
Keynote at-icpc-2020Keynote at-icpc-2020
Keynote at-icpc-2020Ralf Laemmel
 
Functional data structures
Functional data structuresFunctional data structures
Functional data structuresRalf Laemmel
 
Modeling software systems at a macroscopic scale
Modeling software systems  at a macroscopic scaleModeling software systems  at a macroscopic scale
Modeling software systems at a macroscopic scaleRalf Laemmel
 
An introduction on language processing
An introduction on language processingAn introduction on language processing
An introduction on language processingRalf Laemmel
 
Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013
Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013
Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013Ralf Laemmel
 
The Expression Problem (as part of the the PTT lecture)
The Expression Problem (as part of the the PTT lecture)The Expression Problem (as part of the the PTT lecture)
The Expression Problem (as part of the the PTT lecture)Ralf Laemmel
 

Más de Ralf Laemmel (6)

Keynote at-icpc-2020
Keynote at-icpc-2020Keynote at-icpc-2020
Keynote at-icpc-2020
 
Functional data structures
Functional data structuresFunctional data structures
Functional data structures
 
Modeling software systems at a macroscopic scale
Modeling software systems  at a macroscopic scaleModeling software systems  at a macroscopic scale
Modeling software systems at a macroscopic scale
 
An introduction on language processing
An introduction on language processingAn introduction on language processing
An introduction on language processing
 
Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013
Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013
Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013
 
The Expression Problem (as part of the the PTT lecture)
The Expression Problem (as part of the the PTT lecture)The Expression Problem (as part of the the PTT lecture)
The Expression Problem (as part of the the PTT lecture)
 

Último

Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 

Último (20)

Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 

Metaprograms and metadata (as part of the the PTT lecture)

  • 1. Metaprograms and metadata Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team
  • 3. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Elevator speech So programs are programs and data is data. Or perhaps programs could be data? Or rather data could be programs? What if programs process data representing programs? Those are metaprograms. (Reflection is an important way of doing metaprogramming.) What if data represents data about programs? This is metadata. Programming is for kids. Metaprogramming is for men nerds.
  • 4. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Metaprogramming terminology • A metaprogram is a program that manipulates other programs. That is, programs correspond to data of metaprograms. • 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. • The ability of a programming language to be its own metalanguage is called reflection . If reflection is limited to “read access”, then this is called introspection. • Reflection can be achieved in very different ways: – API-based access to program (Java). – Special language and compiler support (C++ templates).
  • 5. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Examples of metaprograms • A Java program that pretty prints arithmetic expressions. • … evaluates them. • … transforms them (e.g., optimizes them). • A Java compiler because: – it inspects Java code, and – it produces byte code. • If the Java compiler is written in Java, it is a reflective meta-program; if it is written in Haskell instead, it is just a meta-program. • A byte-code engineering program because it analyses, generates, or transforms programs in JVM byte code. • …
  • 6. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Scenario • Create an object through reflection API • Invoke a method through reflection API Why is this interesting? • Imagine the class or the method are not known until runtime. The “Hello World” of java.lang.reflect DEMO See package helloworld of https://github.com/101companies/101repo/tree/master/ technologies/Java_platform/samples/javaReflectionSamples
  • 8. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Java’s “built-in” reflection Basics (Covered today) • java.lang.Class • java.lang.reflect.Field • java.lang.reflect.Method • java.lang.reflect.Constructor Advanced (Optional material included) • java.lang.reflect.Proxy Object model for object models Deep support for dynamic classes and the proxy design pattern
  • 9. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) java.lang.Class • Represents classes (and interfaces) in a Java app. • Each object knows of its class: obj.getClass() • Each class knows of its class: String.class • Primitive types have an associated class. • Even void has an associated class. • Class cannot be regularly instantiated. • Instead the class loader uses defineClass: – Input: byte code – Output: an instance of type Class To treat argument and result types homogeneously and precisely
  • 10. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) java.lang.Class interface • Map strings to class objects (forName) • Getter – Name – Constructors – Fields – Methods – Interfaces – Annotations – Package – Superclass – Enclosing class • NO SETTERS • Various other inspectors (“tests”) • Instantiation (but see constructors) • Cast operations • … This is one manifestation of Java’s reflection to focus on introspection.
  • 11. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) java.lang.reflect.Method • Represents methods – … of classes and interfaces – static, initialization, instance, and abstract methods • Constructors are treated very similar; see: – java.lang.reflect.Constructor • Does not provide byte-code access. • Returned by getters on java.lang.Class. • NO METHOD BODIES
  • 12. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) java.lang.reflect.Method interface • Getters – Name – Parameter types – Return type – Type parameters – Class – Modifiers – Annotations – Parameter annotations – … • Invocation
  • 13. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) java.lang.reflect.Field Provides information about fields. Provides dynamic access to fields.
  • 14. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) java.lang.reflect.Field interface • Getters –Name –Value (for a given object) –Modifiers –Annotations –… • Setters –Value (for a given object)
  • 16. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Scenario • Given an object of an arbitrary type. • Provide a deep dump on the state of the object. • That is, go over the fields recursively. An object dumper DEMO See package dumper of https://github.com/101companies/101repo/tree/master/ technologies/Java_platform/samples/javaReflectionSamples
  • 17. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Total and cut with the help of reflection. 295 DEMO http://101companies.org/wiki/ Contribution:javaReflection Please note the conciseness of the code compared to javaComposition, for example.
  • 18. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) A challenge for (Java) reflection Given a class, what are the subclasses of it? Alas, there is no such member on “Class”. The set of classes known to the system is simply the set of classes loaded so far. One could assume a scan over the full classpath to get to know more classes, but automatically loading all these classes is expensive and may not be intended.
  • 19. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Find and load all classes of a package 297 DEMO See package packagelist of https://github.com/101companies/101repo/tree/master/ technologies/Java_platform/samples/javaReflectionSamples
  • 20. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Find (and load) all classes in a given package. The search relies on a directory listing. public static Iterable<Class<?>> getClassesInPackage(Package p) { LinkedList<Class<?>> l = new LinkedList<Class<?>>(); String name = p.getName(); name = name.replace('.',File.separatorChar); File dir = new File(name); if (!dir.exists()) throw new RuntimeException("Can't find package!"); for (String f : dir.list()) { String classname = f.substring(0,f.length()-6); try { Class<?> clss = Class.forName(p.getName() + "." + classname); l.add(clss); } catch (ClassNotFoundException e) { // Ignore exception } } return l; } Instead of using the classpath, we assume a translation of the package name to the location in the file system.
  • 22. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Metaprograms vs. metadata Metaprograms are programs that generate, analyze, or control other programs. Metadata (generally) is data that is attached to programs or other data to provide additional information (in particular, application-specific information) for programs and data. In Java, we can use annotations for metadata. It happens that metaprograms often need annotations.
  • 23. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Sample annotation @Test public void testTotal() throws Exception { Document doc = DOMUtilities.loadDocument(sampleCompany); double total = total(doc); assertEquals(399747, total, 0); }
  • 24. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Annotations Data associated with methods, fields, class, etc. that does not affect the semantics of a program, but controls metaprograms over the annotated object programs. Scenarios: • Identify test methods and control execution (JUnit) • Control serialization of objects as XML (JAXB) • ... many other frameworks ... .NET uses the term “custom attributes”; Java “adopted” them and called them annotations
  • 25. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Sample annotation @RequestForEnhancement( id = 2868724, synopsis = "Enable time-travel", engineer = "Mr. Peabody", date = "4/1/3007" ) Public void travelThroughTime(Date destination) { ... } “=“ notation can be omitted if there is only a single method of name value.
  • 26. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Annotation declaration for sample annotation /** * Describes a Request-For-Enhancement(RFE) * for the API element at hand */ public @interface RequestForEnhancement { int id(); String synopsis(); String engineer() default "[unassigned]"; String date(); default "[unimplemented]"; } Thus, annotation declarations are somewhat specific interface declarations.
  • 27. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Annotation rules • An annotation decl takes the form of interface decl except that … – they start with an 'at' sign @; – their method declarations must not have any parameters; – … and must not have any throws clauses; – their return types of the method must be one of the following: • Primitive types; • String; • Class; • Enum; • Array types of the above types; – there may be a default for each method.
  • 28. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Meta-annotations aka Metametadata • @Documented – controls whether or not the declarations should be visible when targets are documented in any way. • @Inherited – controls whether or not a subclass (or a member thereof) inherits the annotation when the superclass (or a member thereof) was target. • @Retention – (runtime, source, …) controls whether the annotation will be available, accessible during runtime. • @Target – (field, method, type, …, annotation) the kind of declaration to which the annotation can be attached.
  • 29. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Scenario • Take a class name as argument. • Find all “test” methods in the class. • Execute them. • Keep a record of success and failure. A tiny approximation of JUnit 307 DEMO See package junitlight of https://github.com/101companies/101repo/tree/master/ technologies/Java_platform/samples/javaReflectionSamples
  • 30. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Summary • Meta-programming comes in many forms: – Analyze – Transform – Generate – Compose Code, where code is … – Java source code, or – JVM byte code. • Meta-programming is used/needed all over the place: – By the compiler – By IDE and tool support (JUnit, …) – By application generators – By mapping tools (X/O/R) – … Programming is for casual hackers; meta-programming is for real men nerds.
  • 32. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Extra meta-programming power for Java • BCEL, ASM, ... – Byte-code engineering libraries • Javassist – Byte-code editing also at source level • com.sun.source.tree – Compiler Tree API • … various other technologies Related topics: code generation and analysis • “Code-Generation Techniques for Java”, article at OnJava.com • “Generate Java Code”, article at codefutures.com • “Source Code Analysis Using Java 6 APIs", article Java.net References - FYI
  • 33. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Further reading: Beyond Java July 1991 7 x 9, 348 pp., 9 illus. $45.00/£29.95 (PAPER) Short ISBN-10: 0-262-61074-4 ISBN-13: 978-0-262-61074-2 References - FYI
  • 34. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Seminal references • Brian C. Smith. Reflection and semantics in lisp. In Conference Record of the Eleventh Annual ACM Symposium on Principles of Programming Languages, pages 23--35. ACM Press, January 1984. • Daniel P. Friedman and Mitchell Wand. Reification: Reflection without metaphysics. In Conference Record of the 1984 ACM Symposium on LISP and Functional Programming, pages 348--355, Austin, Texas, August 1984. ACM Press. • Mitchell Wand and Daniel P. Friedman. The mystery of the tower revealed: A non-reflective description of the reflective tower. Lisp and Symbolic Computation, 1(1):11--38, June 1988. • Stanley Jefferson and Daniel P. Friedman. A simple reflective interpreter. Lisp and Symbolic Computation, 9(2/3):181--202, May/June 1996. References - FYI
  • 35. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Online resources on Java reflection Series at IBM developerWorks • Part 1: Classes and class loading • Part 2: Introducing reflection • Part 3: Applied reflection • Part 4: Class transformation with Javassist • Part 5: Transforming classes on-the-fly • Part 6: Aspect-oriented changes with Javassist • Part 7: Bytecode engineering with BCEL • Part 8: Replacing reflection with code generation Miscellaneous • Another simple reflection tutorial • “Reflection API Code Samples”, samples @ SDN • More on class loading: – “Inside Class Loaders”, article at OnJava.com – “Create a custom Java 1.2-style ClassLoader”, article at JavaWorld.com References - FYI
  • 37. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Reflection-based proxies Remember the Proxy Pattern? Optional; beware: advanced example.
  • 38. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Scenario • Taken an object of any type. • Return a proxy for that object. • Forward all methods from proxy to real subject. • In addition, produce tracing information. A tracer proxy for any given object DEMO Optional; beware: advanced example. See package tracer of https://github.com/101companies/101repo/tree/master/ technologies/Java_platform/samples/javaReflectionSamples
  • 39. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) java.lang.reflect.Proxy • Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods. • A (dynamic) proxy class is a class that implements a list of interfaces specified at runtime when the class is created. • A proxy interface is such an interface that is implemented by a proxy class. • A proxy instance is an instance of a proxy class. Each proxy instance has an associated invocation handler object, which implements the interface InvocationHandler. A method invocation on a proxy instance through one of its proxy interfaces will be dispatched to the invoke method of the instance's invocation handler. Optional; beware: advanced example.
  • 40. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) java.lang.reflect.Proxy If XYZ is an interface passed as an argument in the creation of the proxy class, and obj is an instance of the proxy class, then the following operations are valid: • obj instanceof XYZ • (XYZ) obj Optional; beware: advanced example.