SlideShare a Scribd company logo
Advanced Java Applications
Overview We will see some advanced techniques and applications of Java We will take a quick look at some data structures built into the language Next will show be how Java and Object Orientation can be applied to networking Finally we will be to show Reflection in Java
Hashtable Example Hashtable numbers = new Hashtable(); numbers.put("one", new Integer(1)); numbers.put("two", new Integer(2)); numbers.put("three", new Integer(3)); key value
Hashtable Example Integer n = (Integer)numbers.get("two"); if (n != null) { System.out.println("two = " + n); } Object Specific Object
Many Other Collections Vector Stack LinkedList Dictionary  ArrayList http://www.javasoft.com/products/jdk/1.2/docs/api/index.html for a complete list
Networking Using the networking capabilities provided in the Java environment is quite easy We will see how to use  Sockets
Sockets Lower-level network communication - Client – uses some service - Server - provides some service TCP provides a reliable, point-to-point communication channel for client-server apps
What Is a Socket? A socket is one endpoint of a two-way communication link between two  programs running on the network.  A socket is bound to a port number so that the TCP layer  can identify the application that data is destined to be sent.
How do Sockets work? A server runs on a specific computer and has a socket that is bound to a specific port number. Client knows the hostname and port of server and  tries to make a connection request
Connection established If the server accepts the connection it gets a new socket bound to a different port.  It needs a new socket (and consequently a different port number) so that it can continue to listen to the original socket
How does Java support Sockets The java.net package provides a class,  Socket , that implements one side of a  two-way connection between your Java program and another program on the network It also includes the  ServerSocket  class, which implements a socket that servers can use to listen for and accept connections to client
Echo Echo Echo import java.io.*; import java.net.*; public class EchoClient { public static void main(String[] args)  throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; // …
Establish the Socket connection try { echoSocket = new Socket(“image ", 7777); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new  InputStreamReader(echoSocket.getInputStream())); } catch … Host   Port Output Input
Need to Catch Exceptions }  catch (UnknownHostException e) { System.err.println("Don't know about host: avatar."); System.exit(1); }  catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: avatar."); System.exit(1); }
Simple Socket Example BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } Set up a mechanism to read from standard input Output what’s read back from Server Write to Server Read from standard input
Close up Shop on Client side out.close( ); in.close( ); stdIn.close( ); echoSocket.close( );
Basic Steps Open a socket.  Open an input stream and output stream to the socket.  Read from and write to the stream according to the server's protocol.  Close the streams.  Close the socket.
Same Basic Steps This client program is straightforward and simple because the Echo server implements a simple protocol Even with more complicated protocols such as HTTP server, your client program while more complicated will follow the same basics as this simple example
Server A server must open a SeverSocket ServerSocket server = new ServerSocket( 7777 );   Call accept on that socket creating a new socket Socket socket = server.accept();   Socket acts as socket from client
If a socket is a  pipe  … We could conceptualize  this like so: Client Server Ports The Socket Plumbing The things flowing through the Plumbing
The Answer Is .. A Number of things can conceptually flow through the pipe We will focus on two: Objects  Characters from a String We looked at several examples last time The first was a simple echo program – a very simple protocol – give me back what I gave you (Strings) We also looked at simpleprotocol example (Protocol Objects)
Objects flow through the Pipe Let first address the case where we want to have objects flowing over the pipe  Must have at least the following mechanisms for  Objects to be written by the server Objects to be read by the client
The newprotocol Client public class Client   { Socket socket = new Socket( "127.0.0.1", 9999 );   // ObjectInputStream  input =  new ObjectInputStream(socket. getInputStream () );  // read using serialization NewProtocol protocol   = ( NewProtocol )(input .readObject () ); System.out.println(“Protocol: “ + protocol); socket.close();
The newprotocol Server class ThreadedSocket extends Thread { // here is where all the real work is done. private Socket socket; ThreadedSocket( Socket socket ) { this.socket = socket; //…  ObjectOutputStream output =  new  ObjectOutputStream(socket.getOutputStream() ); output.writeObject( protocol );
Reading and Writing Objects  An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. General Mechanism This works for the sockets as was just shown but is actually more general Persistent storage of objects can be accomplished by using a file for the stream.
File example For example to write an object that can be read by the example in ObjectInputStream FileOutputStream ostream = new FileOutputStream(“foo.bar"); ObjectOutputStream p = new ObjectOutputStream(ostream); p.writeInt(12345); p.writeObject("Today"); p.writeObject(new Date()); p.flush(); ostream.close();
The read counterpart FileInputStream istream = new FileInputStream(" foo.bar "); ObjectInputStream p = new ObjectInputStream(istream); int i = p.readInt(); String today = (String)p.readObject(); Date date = (Date)p.readObject(); istream.close();
The Needed Java Framework Only objects that support the java.io.Serializable interface can be written to streams.   The class of each serializable object is encoded including the class name and signature of the class, the values of the object's fields and arrays, and the closure of any other objects referenced from the initial objects This relates to introspection/reflection which we will discuss shortly
More about the Framework The default deserialization mechanism for objects restores the contents of each field to the value and type it had when it was written.  Marshalling of Objects (Serialize) Un marshaling of Object (Serialize)
Deserialization& Object Reflection Fields declared as transient or static are ignored by the deserialization process.  References to other objects cause those objects to be read from the stream  as necessary .  Graphs of objects are restored correctly using a reference sharing mechanism.  New objects are always allocated  when deserializing, which prevents existing objects from being overwritten Reflection
Reflection Allows Determination of the class of an object. Creation of an instance of a class whose name is not known until runtime.  Obtaining information about a class's modifiers, fields, methods, constructors, and superclasses. Determination of constants and method declarations that belong to an interface
Reflection Also Allows Allows one to get and set the value of an object's field, even if the field name is unknown to your program until runtime.  Allows one to invoke a method on an object, even if the method is not known until runtime.  Create a new array, whose size and component type are not known until runtime, and then modify the array's components.
Examining Classes  A way to get information about classes at runtime For each class, the Java Runtime Environment (JRE) maintains an immutable Class object that contains information about the class. A Class object represents, or reflects, the class To get this information you need to get the Class object that reflects the class
Retrieving Class Objects You can retrieve a Class object in several ways:  Class c = foo.getClass()  // for some object named foo Bar b = new Bar();  Class c = b.getClass();  Class s = c.getSuperclass(); Foo Bar
Other Ways of Retrieving Class Objects If you know the name of the class at compile time, you can retrieve its Class object by appending  .class  to its name:  Class c = java.awt.Button.class; You can also use the Class.forName static method: Class c = Class.forName(commandNameToken)
Getting the Class Name  Every class in the Java programming language has a name. When you declare a class, the name immediately follows the class keyword At runtime, you can determine the name of a Class object by invoking the getName method. The String returned by getName is the  fully-qualified name of the class. A good home study question: Given an instance prints the names of the classes its inheritance hierarchy from least specific to most specific excluding Object
An Example import java.lang.reflect.*; import java.awt.*; class SampleName { public static void main(String[] args) { Button b = new Button(); printName(b); } static void printName(Object o) { Class c = o.getClass(); String s = c.getName(); System.out.println(s); }} Need Reflection Package To Do this

More Related Content

PPTX
Advance Java Topics (J2EE)
slire
 
PPT
Java Servlets
Nitin Pai
 
PPTX
Java servlets
yuvarani p
 
PDF
JDBC in Servlets
Eleonora Ciceri
 
PDF
Advanced java programming-contents
Self-Employed
 
PPT
Advanced java
NA
 
PDF
Servlets
Ravi Kant Sahu
 
PPS
Jdbc api
kamal kotecha
 
Advance Java Topics (J2EE)
slire
 
Java Servlets
Nitin Pai
 
Java servlets
yuvarani p
 
JDBC in Servlets
Eleonora Ciceri
 
Advanced java programming-contents
Self-Employed
 
Advanced java
NA
 
Servlets
Ravi Kant Sahu
 
Jdbc api
kamal kotecha
 

What's hot (19)

PPTX
Java/Servlet/JSP/JDBC
FAKHRUN NISHA
 
PPT
JDBC – Java Database Connectivity
Information Technology
 
DOC
JDBC
Manjunatha RK
 
PPTX
Core Java introduction | Basics | free course
Kernel Training
 
PPT
Basic java part_ii
Khaled AlGhazaly
 
PPT
Jsp sasidhar
Sasidhar Kothuru
 
PDF
Advanced Java
Hossein Mobasher
 
PPS
Jdbc example program with access and MySql
kamal kotecha
 
PPT
Java basic
Arati Gadgil
 
PPT
比XML更好用的Java Annotation
javatwo2011
 
PDF
Java EE 與 雲端運算的展望
javatwo2011
 
PPS
Java rmi example program with code
kamal kotecha
 
PDF
Introduction to JDBC and database access in web applications
Fulvio Corno
 
PPT
Java Server Pages
BG Java EE Course
 
PPT
Java Server Faces (JSF) - Basics
BG Java EE Course
 
PDF
Java Programming - 08 java threading
Danairat Thanabodithammachari
 
PPT
Struts,Jsp,Servlet
dasguptahirak
 
PPTX
Let's start with Java- Basic Concepts
Aashish Jain
 
PDF
Jdbc[1]
Fulvio Corno
 
Java/Servlet/JSP/JDBC
FAKHRUN NISHA
 
JDBC – Java Database Connectivity
Information Technology
 
Core Java introduction | Basics | free course
Kernel Training
 
Basic java part_ii
Khaled AlGhazaly
 
Jsp sasidhar
Sasidhar Kothuru
 
Advanced Java
Hossein Mobasher
 
Jdbc example program with access and MySql
kamal kotecha
 
Java basic
Arati Gadgil
 
比XML更好用的Java Annotation
javatwo2011
 
Java EE 與 雲端運算的展望
javatwo2011
 
Java rmi example program with code
kamal kotecha
 
Introduction to JDBC and database access in web applications
Fulvio Corno
 
Java Server Pages
BG Java EE Course
 
Java Server Faces (JSF) - Basics
BG Java EE Course
 
Java Programming - 08 java threading
Danairat Thanabodithammachari
 
Struts,Jsp,Servlet
dasguptahirak
 
Let's start with Java- Basic Concepts
Aashish Jain
 
Jdbc[1]
Fulvio Corno
 
Ad

Similar to Advance Java (20)

PPT
Java Basics
shivamgarg_nitj
 
PPT
Advanced Java Topics
Salahaddin University-Erbil
 
DOCX
Please look at the attach See.doc. I am getting this error all th.docx
randymartin91030
 
PDF
java sockets
Enam Ahmed Shahaz
 
PDF
Java Programming - 07 java networking
Danairat Thanabodithammachari
 
PPT
Java basics
Jitender Jain
 
PPTX
Advance Java-Network Programming
ashok hirpara
 
PPT
Networking & Socket Programming In Java
Ankur Agrawal
 
PPT
Unit 8 Java
arnold 7490
 
PDF
Lecture6
vantinhkhuc
 
PPTX
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
PDF
28 networking
Ravindra Rathore
 
PPT
Socket Programming it-slideshares.blogspot.com
phanleson
 
PPT
Sockets
sivindia
 
PPT
Network Programming in Java
Tushar B Kute
 
PPT
Network programming in Java
Tushar B Kute
 
PPTX
A.java
JahnaviBhagat
 
PPT
Socket Programming in Java.ppt yeh haii
inambscs4508
 
PPT
Network
phanleson
 
PPT
Chapter 4 slides
lara_ays
 
Java Basics
shivamgarg_nitj
 
Advanced Java Topics
Salahaddin University-Erbil
 
Please look at the attach See.doc. I am getting this error all th.docx
randymartin91030
 
java sockets
Enam Ahmed Shahaz
 
Java Programming - 07 java networking
Danairat Thanabodithammachari
 
Java basics
Jitender Jain
 
Advance Java-Network Programming
ashok hirpara
 
Networking & Socket Programming In Java
Ankur Agrawal
 
Unit 8 Java
arnold 7490
 
Lecture6
vantinhkhuc
 
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
28 networking
Ravindra Rathore
 
Socket Programming it-slideshares.blogspot.com
phanleson
 
Sockets
sivindia
 
Network Programming in Java
Tushar B Kute
 
Network programming in Java
Tushar B Kute
 
Socket Programming in Java.ppt yeh haii
inambscs4508
 
Network
phanleson
 
Chapter 4 slides
lara_ays
 
Ad

More from Vidyacenter (6)

PPS
Example Projectile Motion
Vidyacenter
 
PPS
Clanguage
Vidyacenter
 
PPS
C++ Language
Vidyacenter
 
PPS
Interview Tips
Vidyacenter
 
PPS
Gre Ppt
Vidyacenter
 
PPS
Gmat Ppt
Vidyacenter
 
Example Projectile Motion
Vidyacenter
 
Clanguage
Vidyacenter
 
C++ Language
Vidyacenter
 
Interview Tips
Vidyacenter
 
Gre Ppt
Vidyacenter
 
Gmat Ppt
Vidyacenter
 

Recently uploaded (20)

PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Doc9.....................................
SofiaCollazos
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
The Future of Artificial Intelligence (AI)
Mukul
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Doc9.....................................
SofiaCollazos
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 

Advance Java

  • 2. Overview We will see some advanced techniques and applications of Java We will take a quick look at some data structures built into the language Next will show be how Java and Object Orientation can be applied to networking Finally we will be to show Reflection in Java
  • 3. Hashtable Example Hashtable numbers = new Hashtable(); numbers.put("one", new Integer(1)); numbers.put("two", new Integer(2)); numbers.put("three", new Integer(3)); key value
  • 4. Hashtable Example Integer n = (Integer)numbers.get("two"); if (n != null) { System.out.println("two = " + n); } Object Specific Object
  • 5. Many Other Collections Vector Stack LinkedList Dictionary ArrayList http://www.javasoft.com/products/jdk/1.2/docs/api/index.html for a complete list
  • 6. Networking Using the networking capabilities provided in the Java environment is quite easy We will see how to use Sockets
  • 7. Sockets Lower-level network communication - Client – uses some service - Server - provides some service TCP provides a reliable, point-to-point communication channel for client-server apps
  • 8. What Is a Socket? A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.
  • 9. How do Sockets work? A server runs on a specific computer and has a socket that is bound to a specific port number. Client knows the hostname and port of server and tries to make a connection request
  • 10. Connection established If the server accepts the connection it gets a new socket bound to a different port. It needs a new socket (and consequently a different port number) so that it can continue to listen to the original socket
  • 11. How does Java support Sockets The java.net package provides a class, Socket , that implements one side of a two-way connection between your Java program and another program on the network It also includes the ServerSocket class, which implements a socket that servers can use to listen for and accept connections to client
  • 12. Echo Echo Echo import java.io.*; import java.net.*; public class EchoClient { public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; // …
  • 13. Establish the Socket connection try { echoSocket = new Socket(“image ", 7777); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream())); } catch … Host Port Output Input
  • 14. Need to Catch Exceptions } catch (UnknownHostException e) { System.err.println("Don't know about host: avatar."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: avatar."); System.exit(1); }
  • 15. Simple Socket Example BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } Set up a mechanism to read from standard input Output what’s read back from Server Write to Server Read from standard input
  • 16. Close up Shop on Client side out.close( ); in.close( ); stdIn.close( ); echoSocket.close( );
  • 17. Basic Steps Open a socket. Open an input stream and output stream to the socket. Read from and write to the stream according to the server's protocol. Close the streams. Close the socket.
  • 18. Same Basic Steps This client program is straightforward and simple because the Echo server implements a simple protocol Even with more complicated protocols such as HTTP server, your client program while more complicated will follow the same basics as this simple example
  • 19. Server A server must open a SeverSocket ServerSocket server = new ServerSocket( 7777 ); Call accept on that socket creating a new socket Socket socket = server.accept(); Socket acts as socket from client
  • 20. If a socket is a pipe … We could conceptualize this like so: Client Server Ports The Socket Plumbing The things flowing through the Plumbing
  • 21. The Answer Is .. A Number of things can conceptually flow through the pipe We will focus on two: Objects Characters from a String We looked at several examples last time The first was a simple echo program – a very simple protocol – give me back what I gave you (Strings) We also looked at simpleprotocol example (Protocol Objects)
  • 22. Objects flow through the Pipe Let first address the case where we want to have objects flowing over the pipe Must have at least the following mechanisms for Objects to be written by the server Objects to be read by the client
  • 23. The newprotocol Client public class Client { Socket socket = new Socket( "127.0.0.1", 9999 ); // ObjectInputStream input = new ObjectInputStream(socket. getInputStream () ); // read using serialization NewProtocol protocol = ( NewProtocol )(input .readObject () ); System.out.println(“Protocol: “ + protocol); socket.close();
  • 24. The newprotocol Server class ThreadedSocket extends Thread { // here is where all the real work is done. private Socket socket; ThreadedSocket( Socket socket ) { this.socket = socket; //… ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream() ); output.writeObject( protocol );
  • 25. Reading and Writing Objects An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. General Mechanism This works for the sockets as was just shown but is actually more general Persistent storage of objects can be accomplished by using a file for the stream.
  • 26. File example For example to write an object that can be read by the example in ObjectInputStream FileOutputStream ostream = new FileOutputStream(“foo.bar"); ObjectOutputStream p = new ObjectOutputStream(ostream); p.writeInt(12345); p.writeObject("Today"); p.writeObject(new Date()); p.flush(); ostream.close();
  • 27. The read counterpart FileInputStream istream = new FileInputStream(" foo.bar "); ObjectInputStream p = new ObjectInputStream(istream); int i = p.readInt(); String today = (String)p.readObject(); Date date = (Date)p.readObject(); istream.close();
  • 28. The Needed Java Framework Only objects that support the java.io.Serializable interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object's fields and arrays, and the closure of any other objects referenced from the initial objects This relates to introspection/reflection which we will discuss shortly
  • 29. More about the Framework The default deserialization mechanism for objects restores the contents of each field to the value and type it had when it was written. Marshalling of Objects (Serialize) Un marshaling of Object (Serialize)
  • 30. Deserialization& Object Reflection Fields declared as transient or static are ignored by the deserialization process. References to other objects cause those objects to be read from the stream as necessary . Graphs of objects are restored correctly using a reference sharing mechanism. New objects are always allocated when deserializing, which prevents existing objects from being overwritten Reflection
  • 31. Reflection Allows Determination of the class of an object. Creation of an instance of a class whose name is not known until runtime. Obtaining information about a class's modifiers, fields, methods, constructors, and superclasses. Determination of constants and method declarations that belong to an interface
  • 32. Reflection Also Allows Allows one to get and set the value of an object's field, even if the field name is unknown to your program until runtime. Allows one to invoke a method on an object, even if the method is not known until runtime. Create a new array, whose size and component type are not known until runtime, and then modify the array's components.
  • 33. Examining Classes A way to get information about classes at runtime For each class, the Java Runtime Environment (JRE) maintains an immutable Class object that contains information about the class. A Class object represents, or reflects, the class To get this information you need to get the Class object that reflects the class
  • 34. Retrieving Class Objects You can retrieve a Class object in several ways: Class c = foo.getClass() // for some object named foo Bar b = new Bar(); Class c = b.getClass(); Class s = c.getSuperclass(); Foo Bar
  • 35. Other Ways of Retrieving Class Objects If you know the name of the class at compile time, you can retrieve its Class object by appending .class to its name: Class c = java.awt.Button.class; You can also use the Class.forName static method: Class c = Class.forName(commandNameToken)
  • 36. Getting the Class Name Every class in the Java programming language has a name. When you declare a class, the name immediately follows the class keyword At runtime, you can determine the name of a Class object by invoking the getName method. The String returned by getName is the fully-qualified name of the class. A good home study question: Given an instance prints the names of the classes its inheritance hierarchy from least specific to most specific excluding Object
  • 37. An Example import java.lang.reflect.*; import java.awt.*; class SampleName { public static void main(String[] args) { Button b = new Button(); printName(b); } static void printName(Object o) { Class c = o.getClass(); String s = c.getName(); System.out.println(s); }} Need Reflection Package To Do this