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
Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
Advertisements

About ClassLoaders. What Do They Do? In java code, we simply do this: In java code, we simply do this: java.util.Hashtable table=new java.util.Hashtable();
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.
Design By Contract Using JMSAssert.
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
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.
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.
Tutorial 6 Assignment 2. If using C gcc is most likely installed by default. Otherwise, you need to install it Submit your source code file with extension.c.
Remote Method Invocation
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.
Java Virtual Machine (JVM). Lecture Objectives Learn about the Java Virtual Machine (JVM) Understand the functionalities of the class loader subsystem.
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.
Problem Solving #3: JVM ICS Outline Review of Key Topics Review of Key Topics Problem 1 Problem 1 Problem 2 Problem 2 Problem 3 Problem 3 Problem.
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.
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.
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
1 Java Programming II Java Network II (Distributed Objects in Java)
1 3. Implementing Web Services 1.Create SOAP proxy interfaces and WSDL based service descriptions 2.Register/publish services 3.Stores service descriptions.
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
The Terminator to Android Hardening Services
Java Introduction to JNI Prepared by Humaira Siddiqui.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Java 2 security model Valentina Casola. Components of Java the development environment –development lifecycle –Java language features –class files and.
Tu sca ny 1 Extending The Tuscany Java SCA Runtime 21 August 2006.
Java programming Package. A package is a group of similar types of classes, interfaces and sub-packages. Package can be categorized in two form, built-
Plug-In Architecture Pattern. Problem The functionality of a system needs to be extended after the software is shipped The set of possible post-shipment.
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.
EE2E1. JAVA Programming Lecture 3 Java Programs and Packages.
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.
22-July-2002cse142-13B-Development © 2002 University of Washington1 Development Tools CSE 142, Summer 2002 Computer Programming 1
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.
CSI 3125, Preliminaries, page 1 Compiling the Program.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Package A package is a logical container that contains classes,interfaces sub packages. Package provide a unique name space to its members and provide.
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.
3/5/2002e-business and Information Systems1 Java Java Java Virtual Machine (JVM) Java Application Program Interface (API) HW Kernel API Application Programs.
UMBC Distributed Computing with Objects RMI/Corba CMSC 432 Shon Vick.
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.
Object Oriented Programming Lecture 2: BallWorld.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Modern Programming Tools And Techniques-I
Intro to ETEC Java.
Topic: Java Class Loader
Java Primer 1: Types, Classes and Operators
Java Programming Language
Remote Method Invocation
Internet and Java Foundations, Programming and Practice
Programming without BlueJ Week 12
Generics, Lambdas, Reflections
Running An Encrypted Java Program
Programming Language Concepts (CIS 635)
Lecture 20 – April 2, 2002 Bond Objects.
ATS Application Programming: Java Programming
Java Programming Language
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 generate a Class object, given its name

Dynamic Code Invocation Using dynamic class loading, we can dynamically generate a.class file, load it, instantiate it ( class.newInstance() ), and invoke its methods Hence, we can dynamically write and invoke programs How can we access a method of an object, if we do not know its type on compile time? One way is to implement a known interface

Our Example In the following example, we will invoke the method run() of a dynamically created object of type Base public interface Base { public void run(); }

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" + " }}"; createClass(code); Class classB = Class.forName("C"); Base b = (Base)classB.newInstance(); b.run(); }

An Example public static void createClass(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 Whole Process

Assumptions The later code assumes the following: The command javac is known to the System -e.g., the javac executable is in the PATH variable The directory ". " is included in the class path of Java -Hence, Class.forName("C") will find that 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 System Class Loader Java classes are loaded using a class loader Class.forName(name) usually invokes loadClass(name) of the system class loader The system class loader can be accessed by ClassLoader.getSystemClassLoader() Hence, a class can equivalently be loaded by ClassLoader.getSystemClassLoader().loadClass(name)

Bootstrap Class Loader Another class loader that exists in the system is the bootstrap class loader This class loader is built in with the JVM This class is used to load built-in JVM classes, and is used early in the runtime startup Classes that you write are usually loaded by the system class loader, and not by the bootstrap one

Class Loading Method Every class loader has a parent class loader, which could be null By default, class loading is done as follows: -check if a class with the given name has already been loaded by the same class loader -check if the parent can load the class If parent is null, use the bootstrap class loader -invoke the method findClass("class-name") When you load a class, all referenced classes are recursively loaded by the same class loader

Back to our Example So what should we do to reload a class? Answer: -use a new class loader to load the class C -make sure that this loader does not have a parent capable of loading class C For that, we can obtain a ClassLoader object by instantiating java.net.URLClassLoader

URLClassLoader A URLClassLoader has 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 loaders -But the system already has one interface called Base Each newly created interface is considered as a unique interface 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 2 is given in Exercise 3

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);