Dynamic Code Generation in Java. Class Loading Class loading is the process of transforming a byte code (e.g., a.class file) into a Java class A Java.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

Using Java without BlueJ BlueJ projects A BlueJ project is stored in a directory on disk. A BlueJ package is stored in several different files.
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
1 InTroToJCL Introduction to Java Class Loaders. 2 class loader l ia an object responsible for loading classes. The class ClassLoader is an abstract class.
Java Virtual Machine (JVM). Lecture Objectives Learn about the Java Virtual Machine (JVM) Understand the functionalities of the class loader subsystem.
Copyright © 2001 Qusay H. Mahmoud Case Study A Global Compute Engine Here we will discuss some implementation details: – Class Loaders – Compute Engine.
1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
Remote Method Invocation Chin-Chih Chang. Java Remote Object Invocation In Java, the object is serialized before being passed as a parameter to an RMI.
Dynamic Code Generation in Java. Class Loading Class loading is the process of transforming a byte code (e.g., a.class file) into a Java class A Java.
Java Virtual Machine (JVM). Lecture Objectives Learn about the Java Virtual Machine (JVM) Understand the functionalities of the class loader subsystem.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
Using Java without BlueJ Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling BlueJ projects A BlueJ.
What is a class? a class definition is a blueprint to build objects its like you use the blueprint for a house to build many houses in the same way you.
Using Java without BlueJ Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling BlueJ projects A BlueJ.
Using Java without BlueJ
Unit 061 Java Virtual Machine (JVM) What is Java Virtual Machine? The Class Loader Subsystem Linking oVerification oPreparation oResolution Class Initialization.
1 Further OO Concepts II – Java Program at run-time Overview l Steps in Executing a Java Program. l Loading l Linking l Initialization l Creation of Objects.
Introduction to Java Programming Language Junji Zhi University of Toronto 1.
Session-02. Objective In this session you will learn : What is Class Loader ? What is Byte Code Verifier? JIT & JAVA API Features of Java Java Environment.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Programming Languages and Paradigms Object-Oriented Programming.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Java and C++, The Difference An introduction Unit - 00.
Comp 249 Programming Methodology Chapter 8 - Polymorphism Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
Chapter 9: Polymorphism Coming up: Creating Objects Revisited.
The Terminator to Android Hardening Services
CSCE 2013L: Lab 1 Overview  Java Basics The JVM Anatomy of a Java Program  Object-Oriented Programming Overview  Example: Payroll.java JDK Tools and.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Java Remote Method Invocation RMI. Idea If objects communicate with each other on one JVM why not do the same on several JVM’s? If objects communicate.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
© Keren Kalif Advanced Java Topics Written by Keren Kalif, Edited by Liron Blecher.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Programming in Java CSCI-2220 Object Oriented Programming.
CSCI-383 Object-Oriented Programming & Design Lecture 18.
Lecture 15.1 Static Methods and Variables Static Methods In Java it is possible to declare methods and variables to belong to a class rather than.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
CS 4244: Internet Programming Network Programming in Java 1.0.
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
Garbage Collection and Classloading Java Garbage Collectors  Eden Space  Surviver Space  Tenured Gen  Perm Gen  Garbage Collection Notes Classloading.
1. An Introduction A Programming Language A Technology Java Development Kit Java API One Language: Three Editions Standard Edition Enterprise Edition.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
M1G Introduction to Programming 2 5. Completing the program.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Programming Languages and Paradigms Activation Records in Java.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Classes, Interfaces and Packages
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Smalltalk on the JVM By James Ladd - ESUG 2011.
Objects First With Java A Practical Introduction Using BlueJ Using Java without BlueJ 1.0.
Using Java without BlueJ BlueJ projects A BlueJ project is stored in a directory on disk. A BlueJ package is stored in several different files.
BY:- TOPS Technologies
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Java Primer 1: Types, Classes and Operators
Programming without BlueJ Week 12
Lecture 20 – April 2, 2002 Bond Objects.
Java Programming Language
From C++ to Java Java history: Oak, toaster-ovens, internet language, panacea What it is O-O language, not a hybrid (cf. C++) compiled to byte-code, executed.
Plug-In Architecture Pattern
Presentation transcript:

Dynamic Code Generation in Java

Class Loading Class loading is the process of transforming a byte code (e.g., a.class file) into a Java class A Java class can be loaded dynamically (i.e., during runtime) The class is then represented by an object of class Class You can use the method Class.forName("name") to get a pointer to the Class object, given its name (exactly one object represents each class).

Dynamic Code Invocation Using dynamic class loading, we can dynamically generate a.class file, load it, instantiate it ( class.newInstance() ), and invoke its methods Therefore, we can write and execute methods within the execution of the calling program. Q: How can we access a method of an object, if we do not know its type on compile time? One solution is to implement a known interface.

An Example In the following example, we will invoke the method run() of a dynamically created object of class C, inherited from an interface Base

An Example public class Invoker { public static void main(String[] argv) throws Exception { String code = "public class C implements Base {\n" + " public void run() {\n" + " System.out.println(\" \");\n" + " }}"; createClassFile(code); // Implemented in the next slide Class classB = Class.forName("C"); Base b = (Base)classB.newInstance(); b.run(); } public interface Base { public void run(); }

An Example public static void createClassFile(String code) throws Exception { OutputStream os = new FileOutputStream(new File("C.java")); os.write(code.getBytes()); os.close(); Process p = Runtime.getRuntime(). exec("javac -classpath. C.java"); p.waitFor(); }

The Result

The Whole Process

Assumptions The example we just saw works correctly under the following assumptions: The command javac is known to the System -e.g., the javac executable is in the PATH variable The directory ". " is in the class path of Java -Hence, Class.forName("C") will find that C.class

Class Reloading String code1 = "public class C implements Base {\n" + "public void run() {\n" + "System.out.println(\" \");\n" + "}}"; String code2 = "public class C implements Base {\n" + "public void run() {\n" + "System.out.println(\" \");\n" + "}}"; createClass(code1); ((Base)Class.forName("C").newInstance()).run(); createClass(code2); ((Base)Class.forName("C").newInstance()).run(); What is the problem here?

The Result

Class Loaders Java classes are loaded by class loaders Two special class loaders exist: (why not just one?) -The bootstrap class loader Typically implemented completely in C. Loads the primitive classes that are necessary for the initialization of the JVM ( rt.jar ) -The system class loader Loads the regular classes in the program (e.g., all of the classes that you have written so far in various exercises) In addition, any number of user-defined class loaders may be defined Each class loader has a parent class loader -Except for the bootstrap class loader -Having a null parent is the same as having the bootstrap class loader as a parent

The System Class Loader Class.forName(name) invokes loadClass(name) of the class loader of the current class, which is usually the system class loader The system class loader can always be accessed by the static call: ClassLoader.getSystemClassLoader() Hence, a class can explicitly be loaded by the system class loader as follows: ClassLoader.getSystemClassLoader().loadClass(name)

Class Loading Mechanism When loadClass(“C") is invoked on a class loader, the following is done by default: -check if a class names c has already been loaded by the same class loader -Otherwise, check if the parent can load the class Hence certain classes will always be loaded by the bootstrap class loader – Why does this happen? Why is this good? -invoke the method findClass(“C") The implementation of findClass differs between class loaders. When you load a class, all referenced classes are recursively loaded by the same class loader -Including implemented interfaces and parent classes

Back to our Example In the previous example, the class loader didn’t reload the class since it previously loaded a class named C So what should we do to reload a class? Solution 1: Use a unique (randomized?) name each time we rewrite the code Solution 2: Use a different user-defined class loader each time -make sure that this loader does not have a parent capable of loading class C -One way to implement this is using a new ClassLoader object obtained by instantiating java.net.URLClassLoader

URLClassLoader A URLClassLoader loads classes which are accessible via a URL (either a local file system URL or a remote URL) It stores an array of URLs (“ “file://...”, etc.) of either directories or JAR files, and it loads classes from the resources of the URLs Constructor: URLClassLoader(URLs,parent) We will set the URLs to contain only the URL of “.”, and the parent to be null

Fixed(?) Example URL[] urls = {new File(".").toURL()}; createClass(code1); ClassLoader loader = new URLClassLoader(urls,null); Class classB = loader.loadClass("C"); ((Base)classB.newInstance()).run(); createClass(code1); loader = new URLClassLoader(urls,null); classB = loader.loadClass("C"); ((Base)classB.newInstance()).run(); What is the problem here?

A Problem The interface Base is also being loaded by the new class loader -But the system already has one interface called Base Each newly created interface is deemed a unique interface that is different from the Base interface that is identified at compilation time and loaded by the system class loader. Hence, it is impossible to cast C to Base

Solutions Solution 1: to invoke run(), use reflection rather than down casting Solution 2: use the system class loader as a parent, but call findClass() directly, instead of loadClass() -problem: this method is protected -Solution? Solution 3: Create a common parent to all these class loaders, capable of loading only the Base interface.

Fixed(!) Example URL[] urls = {new File(".").toURL()}; createClass(code1); ClassLoader loader = new URLClassLoader(urls,null); Class classB = loader.loadClass("C"); Method runMethod = classB.getMethod("run", null); runMethod.invoke(classB.newInstance(),null); createClass(code2); classB = new URLClassLoader(urls,null).loadClass("C"); classB.getMethod("run",null).invoke(classB.newInstance(),null);

Finally, Different Outputs