This document discusses metaprograms and metadata in Java. Metaprograms are programs that manipulate other programs, where programs correspond to data of metaprograms. Metadata is data that provides additional information about programs or other data. The document provides examples of using reflection and annotations in Java to implement metaprogramming and work with metadata. It also discusses using proxies to implement the proxy pattern reflectively in Java.
STATICMOCK : A Mock Object Framework for Compiled Languages ijseajournal
Mock object frameworks are very useful for creating unit tests. However, purely compiled languages lack robust frameworks for mock objects. The frameworks that do exist rely on inheritance, compiler directives, or linker manipulation. Such techniques limit the applicability of the existing frameworks, especially when
dealing with legacy code.
We present a tool, StaticMock, for creating mock objects in compiled languages. This tool uses source-tosource
compilation together with Aspect Oriented Programming to deliver a unique solution that does not rely on the previous, commonly used techniques. We evaluate the compile-time and run-time overhead incurred by this tool, and we demonstrate the effectiveness of the tool by showing that it can be applied to
new and existing code
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. In this talk, I will first overview several new, key features of Java 8 that can help make programs easier to read, write, and maintain, especially in regards to collections. These features include Lambda Expressions, the Stream API, and enhanced interfaces, many of which help bridge the gap between functional and imperative programming paradigms and allow for succinct concurrency implementations. Next, I will discuss several open issues related to automatically migrating (refactoring) legacy Java software to use such features correctly, efficiently, and as completely as possible. Solving these problems will help developers to maximally understand and adopt these new features thus improving their software.
A Portable Approach for Bidirectional Integration between a Logic and a Stati...Sergio Castro
This dissertation seeks to improve on the state of the art for creating systems integrating modules written in both a logic and a statically-typed object-oriented language. Logic languages are well suited for declaratively solving computational problems that require knowledge representation and reasoning. Modern object-oriented programming languages benefit from mature software ecosystems featuring rich libraries and developer tools. The existence of several integration approaches testifies the interest of both communities in techniques for facilitating the creation of hybrid systems. In this way, systems developed in an object-oriented language can integrate modules written in a logic language that are more convenient for solving declarative problems. On the logic side, non-trivial declarative applications can take advantage of the existence of large software ecosystems such as those surrounding contemporary object-oriented languages. The combination of both paradigms allows a programmer to use the best language available for a given task. Existing integration approaches provide different levels of abstractions for dealing with the integration concern (i.e., the required interoperability in order for logic routines to access the object-oriented world, and vice versa). Some of them still require significant amounts of boilerplate code which hinders their adoption and steepens their learning curve. Others provide a high degree of integration transparency and automation which simplifies their usage. However, many of those approaches often impose strong assumptions about the architecture of a system (e.g., a logic program must run embedded in an object-oriented one) thus suffering from portability issues. Furthermore, most approaches provide limited support for custom context-dependent reification of objects in the logic world and custom mappings of arbitrary logic terms to objects in the object-oriented world. To address these problems, we introduce our portable and customisable approach for bidirectional integration between a logic and a statically-typed object-oriented language. This approach enables a transparent and (semi-) automatic communication between routines in these two worlds. In addition, it provides a customisable context-dependent mechanism for defining how artefacts in one language should be reified in the other language. A concrete implementation is provided as a portable Java--Prolog interoperability framework. To ensure portability, our framework has been made compatible with three open source Prolog engines (SWI, YAP and XSB) by means of drivers. We validated our approach through case studies requiring a seamless integration of declarative programs in Prolog with object-oriented programs in Java.
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. This talk will detail several new key features of Java 8 that can help make programs easier to read, write, and maintain. Java 8 comes with many features, especially related to collection libraries. We will cover such new features as Lambda Expressions, the Stream API, enhanced interfaces, and more.
There are thousands of programming languages, but even if your organization works in one of the more popular languages, it's likely you will eventually interact with others who are unfamiliar with it. Since you can't be proficient in every programming language under the sun, a language that bridges technologies and allows people to communicate their ideas is needed.
A few programming languages have tried to fill this role over the years, but none holds as much promise as Python.
A Taxonomy for Program Metamodels in Program Reverse EngineeringHironori Washizaki
Hironori Washizaki, Yann-Gael Gueheneuc, Foutse Khomh, “A Taxonomy for Program Metamodels in Program Reverse Engineering,” 32nd IEEE International Conference on Software Maintenance and Evolution (ICSME) (CORE Rank A), October 2-10, Raleigh, North Carolina, USA. (to appear) (acceptance rate 29%=37/127) http://www.washi.cs.waseda.ac.jp/
The presentation was given to Rivier Scala / Clojure User Group meeting on 10.6.2013. It is half-baked presentation. Will upload the final version when ready.
The first part is about DSLs in general, complexities in software engineering and abstraction. The seconds part presents an quick overview about DSLs in Scala and touches some of the technologies used for deep embedding.
A Feature-Based Model for Nested Named-Entity Recognition at VLSP-2018 NER Ev...Minh Pham
The presentation of a feature-based model for nested named-entity recognition at VLSP 2018. Our system obtained the first rank among participant systems. There is still a gap between the accuracy on the development set and the test set.
STATICMOCK : A Mock Object Framework for Compiled Languages ijseajournal
Mock object frameworks are very useful for creating unit tests. However, purely compiled languages lack robust frameworks for mock objects. The frameworks that do exist rely on inheritance, compiler directives, or linker manipulation. Such techniques limit the applicability of the existing frameworks, especially when
dealing with legacy code.
We present a tool, StaticMock, for creating mock objects in compiled languages. This tool uses source-tosource
compilation together with Aspect Oriented Programming to deliver a unique solution that does not rely on the previous, commonly used techniques. We evaluate the compile-time and run-time overhead incurred by this tool, and we demonstrate the effectiveness of the tool by showing that it can be applied to
new and existing code
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. In this talk, I will first overview several new, key features of Java 8 that can help make programs easier to read, write, and maintain, especially in regards to collections. These features include Lambda Expressions, the Stream API, and enhanced interfaces, many of which help bridge the gap between functional and imperative programming paradigms and allow for succinct concurrency implementations. Next, I will discuss several open issues related to automatically migrating (refactoring) legacy Java software to use such features correctly, efficiently, and as completely as possible. Solving these problems will help developers to maximally understand and adopt these new features thus improving their software.
A Portable Approach for Bidirectional Integration between a Logic and a Stati...Sergio Castro
This dissertation seeks to improve on the state of the art for creating systems integrating modules written in both a logic and a statically-typed object-oriented language. Logic languages are well suited for declaratively solving computational problems that require knowledge representation and reasoning. Modern object-oriented programming languages benefit from mature software ecosystems featuring rich libraries and developer tools. The existence of several integration approaches testifies the interest of both communities in techniques for facilitating the creation of hybrid systems. In this way, systems developed in an object-oriented language can integrate modules written in a logic language that are more convenient for solving declarative problems. On the logic side, non-trivial declarative applications can take advantage of the existence of large software ecosystems such as those surrounding contemporary object-oriented languages. The combination of both paradigms allows a programmer to use the best language available for a given task. Existing integration approaches provide different levels of abstractions for dealing with the integration concern (i.e., the required interoperability in order for logic routines to access the object-oriented world, and vice versa). Some of them still require significant amounts of boilerplate code which hinders their adoption and steepens their learning curve. Others provide a high degree of integration transparency and automation which simplifies their usage. However, many of those approaches often impose strong assumptions about the architecture of a system (e.g., a logic program must run embedded in an object-oriented one) thus suffering from portability issues. Furthermore, most approaches provide limited support for custom context-dependent reification of objects in the logic world and custom mappings of arbitrary logic terms to objects in the object-oriented world. To address these problems, we introduce our portable and customisable approach for bidirectional integration between a logic and a statically-typed object-oriented language. This approach enables a transparent and (semi-) automatic communication between routines in these two worlds. In addition, it provides a customisable context-dependent mechanism for defining how artefacts in one language should be reified in the other language. A concrete implementation is provided as a portable Java--Prolog interoperability framework. To ensure portability, our framework has been made compatible with three open source Prolog engines (SWI, YAP and XSB) by means of drivers. We validated our approach through case studies requiring a seamless integration of declarative programs in Prolog with object-oriented programs in Java.
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. This talk will detail several new key features of Java 8 that can help make programs easier to read, write, and maintain. Java 8 comes with many features, especially related to collection libraries. We will cover such new features as Lambda Expressions, the Stream API, enhanced interfaces, and more.
There are thousands of programming languages, but even if your organization works in one of the more popular languages, it's likely you will eventually interact with others who are unfamiliar with it. Since you can't be proficient in every programming language under the sun, a language that bridges technologies and allows people to communicate their ideas is needed.
A few programming languages have tried to fill this role over the years, but none holds as much promise as Python.
A Taxonomy for Program Metamodels in Program Reverse EngineeringHironori Washizaki
Hironori Washizaki, Yann-Gael Gueheneuc, Foutse Khomh, “A Taxonomy for Program Metamodels in Program Reverse Engineering,” 32nd IEEE International Conference on Software Maintenance and Evolution (ICSME) (CORE Rank A), October 2-10, Raleigh, North Carolina, USA. (to appear) (acceptance rate 29%=37/127) http://www.washi.cs.waseda.ac.jp/
The presentation was given to Rivier Scala / Clojure User Group meeting on 10.6.2013. It is half-baked presentation. Will upload the final version when ready.
The first part is about DSLs in general, complexities in software engineering and abstraction. The seconds part presents an quick overview about DSLs in Scala and touches some of the technologies used for deep embedding.
A Feature-Based Model for Nested Named-Entity Recognition at VLSP-2018 NER Ev...Minh Pham
The presentation of a feature-based model for nested named-entity recognition at VLSP 2018. Our system obtained the first rank among participant systems. There is still a gap between the accuracy on the development set and the test set.
A Survey of Object Oriented Programming LanguagesMaya Hris.docxdaniahendric
A Survey of Object Oriented Programming Languages
Maya Hristakeva, RadhaKrishna Vuppala
Univ. of California, Santa Cruz
{mayah,vrk}@soe.ucsc.edu
1 Abstract
Object-oriented programming has become a very important programming paradigm of our times.
From the time it was brought into existence by Simula, object-oriented programming has seen wide
acceptance. Object-oriented programming languages (OOPLs) directly support the object notions of
classes, inheritance, information hiding (encapsulation), and dynamic binding (polymorphism). There
is a wide variety of implementations for each of these concepts, and there is no general agreement as to
how a particular concept must be interpreted. This survey takes a detailed look at some of the concepts
considered fundamental to object-orientation, namely inheritance and polymorphism. Different aspects
of inheritance and polymorphism are implemented in various popular OOPLs. We conclude with the
observation that there is still lot of work to be done to reach a common ground for these crucial features
of OOPLs. This survey presents a detailed comparison of Java, C++, C# , Eiffel, Smalltalk, Ruby and
Python in terms of their inheritance and polymorphism implementations. The paper also presents a
compilation of the observations made by several earlier surveys [1, 27].
2 Introduction
There is a big variety of programming languages catering to various kinds of development require-
ments. Three of the main categories are procedural languages (e.g. C, Pascal, etc.), functional languages
(e.g. Haskel, Ocaml, etc.), and object-oriented programming languages (e.g. C++, Java, etc.). The
object-oriented design paradigm has been popular for quite some time owing its success to the powerful
features it offers for making program development easy and robust. OOPLs, such as C++ and Java,
offer an intuitive way of developing programs and provide powerful features for supporting the program
development. While languages like C can be used to develop programs that follow an object-oriented
design, the support of features such as inheritance, encapsulation, strong type support, exception han-
dling, etc. in the OOPLs make them more suitable for such development.
While the object-oriented programming paradigm provides a more intuitive way of programming, it
is also has complexities. This is due to the various complex features that the paradigm offers. OOPLs
differ widely in the way they implement features that are associated with the object design. For example,
some languages support multiple inheritance while some languages consider it a bad feature. In this sur-
vey we discuss the various features of object-oriented programs and how the languages we considered
1
(Java, C++, C# , Eiffel, Smalltalk, Ruby and Python) differ in implementing these features.
The survey is organized as follows. The Section 3 describes in detail the key concepts of OOPLs. Sec-
tion 4 presents a brief historical view of the OOPLs and gives a ...
Bringing It All Together: Mapping Continuing Resources Vocabularies for Linke...NASIG
Andrew Senior, presenter
Over the course of the past five years, several vocabularies have coalesced into clear options for the description of continuing resources in linked data. BIBFRAME 2.0, PRESSoo, and RDA are such examples of robust vocabularies for serials and integrating resource description. Schema.org, a widely-used vocabulary on the Web and employed by OCLC in their linked data work, may also offer sufficient granularity for serial descriptions using schema extensions.
Leaders in the field of bibliographic linked data have begun to investigate the relationships between these vocabularies, such as OCLC’s study of BIBFRAME and schema.org. Specifically for continuing resources, the CONSER BIBFRAME Task Group is investigating the mapping of the CONSER Standard Record to BIBFRAME and the relationship to PRESSoo.
As institutions assess the means with which we can publish our serials bibliographic information as linked data, how will these varying vocabularies with diverse levels of granularity co-exist in the discovery ecosystem? Using examples from current and historical serials and newspapers, this presentation proposes a meta-analysis and comparative mapping of key continuing resources elements in the BIBFRAME, PRESSoo, RDA and schema.org vocabularies. It will examine whether alignment is possible at this stage—in order to collocate shared or related elements—and immediately leverage existing web standards to enhance discoverability for continuing resources in linked data.
Compiler Construction | Lecture 6 | Introduction to Static AnalysisEelco Visser
Lecture introducing the need for static analysis in addition to parsing, the complications caused by names, and an introduction to name resolution with scope graphs
JAVA - A Quick Reference
A quick guide to learn more about JAVA Programming. This covers the core concepts of JAVA with OOP concepts. This also covers swing programming.
Sparklis exploration et interrogation de points d'accès sparql par interactio...SemWebPro
Sparklis est une application Web de recherche sémantique qui fonctionne au-dessus de points d'accès SPARQL. Il n'est pas lié à un point d'accès particulier, mais peut fonctionner avec n'importe quel point d'accès public ou privé. Le principe de Sparklis est de permettre aux utilisateurs d'explorer et interroger les données en les guidant dans la construction de requêtes puissantes en langue naturelle (anglais ou français). Une requête SPARQL est construite en même temps mais elle est seulement affichée en bas de la page pour l'utilisateur curieux ou pour l'expert qui souhaite la réutiliser dans un autre outil. Les utilisateurs n'ont pas besoin de connaître le schéma de données ou le vocabulaire car ils le découvrent à la volée en naviguant. Ils n'ont rien à écrire, à part les valeurs de filtrage (ex., mots-clés, seuils), ce qui exclut toute erreur lexicale, syntaxique ou sémantique. Sparklis couvre un large sous-ensemble de SPARQL : motifs de graphes, OPTIONAL, UNION, NOT EXISTS, tri des résultats, agrégations, filtres principaux (mots clés, inégalités et intervalles, tag de langue et datatype). Enfin, il est conçu pour passer à l'échelle de gros jeux de données et fonctionne par exemple sur DBpedia (plusieurs milliards de triplets).
Sparklis est en ligne depuis avril 2014 et depuis, des centaines d'utilisateurs l'ont utilisé sur des centaines de points d'accès. Sparklis s'appuie sur les standards du W3C : SPARQL pour l'interrogation, HTML5/CSS3 et Javascript pour l'interface et l'interaction.
Une démonstration montrera aux participants comment Sparklis permet de répondre aux questions du challenge QALD sur DBpedia. Ces questions couvrent différents types de recherche : faits de base (Give me the homepage of Forbes), listes d'entités (Which rivers flow into a German lake?), comptages (How many languages are spoken in Colombia), optimums (Which of Tim Burton's films had the highest budget}). Il est aussi possible de répondre à des questions analytiques plus complexes telles que Give me the total runtime, from highest to lowest, of films per director and per country.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™UiPathCommunity
In questo evento online gratuito, organizzato dalla Community Italiana di UiPath, potrai esplorare le nuove funzionalità di Autopilot, il tool che integra l'Intelligenza Artificiale nei processi di sviluppo e utilizzo delle Automazioni.
📕 Vedremo insieme alcuni esempi dell'utilizzo di Autopilot in diversi tool della Suite UiPath:
Autopilot per Studio Web
Autopilot per Studio
Autopilot per Apps
Clipboard AI
GenAI applicata alla Document Understanding
👨🏫👨💻 Speakers:
Stefano Negro, UiPath MVPx3, RPA Tech Lead @ BSP Consultant
Flavio Martinelli, UiPath MVP 2023, Technical Account Manager @UiPath
Andrei Tasca, RPA Solutions Team Lead @NTT Data
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
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.