Vous êtes sur la page 1sur 127

Java Reflection API

Reflectionis the process of examining or


modifying the runtime behaviour of a class at
runtime.
The java.lang.Class class provides many
methods that can be used to get metadata,
examine and change the runtime behaviour of a
class.
Where is it used?
The Reflection API is mainly used in:IDE
(Integreted Development Environment) e.g.
Eclipse, MyEclipse, NetBeans etc.
Debugger
Test Tools etc.
Applet,AWT and JavaSwing Tutorial

java.lang.Class class
The java.lang.Class class performs
mainly two tasks:provides methods
to get the metadata of a class at
runtime.
provides methods to examine and
change the runtime behaviour of a
class.

Applet,AWT and JavaSwing Tutorial

Method

Description

1) public String getName()

returns the class name

2) public static Class


forName(String
className)throws
ClassNotFoundException

loads the class and returns the


reference of Class class.

3) public Object
creates new instance.
newInstance()throws
InstantiationException,IllegalAcce
ssException
4) public boolean isInterface()

checks if it is interface.

5) public boolean isArray()

checks if it is array.

6) public boolean isPrimitive()

checks if it is primitive.

7) public Class getSuperclass()

returns the superclass class


reference.

Applet,AWT and JavaSwing Tutorial

8) public Field[]
getDeclaredFields()throws
SecurityException

returns the total number of fields


of this class.

9) public Method[]
getDeclaredMethods()throws
SecurityException

returns the total number of


methods of this class.

10) public Constructor[]


getDeclaredConstructors()throws
SecurityException

returns the total number of


constructors of this class.

11) public Method


returns the method class instance.
getDeclaredMethod(String
name,Class[]
parameterTypes)throws
NoSuchMethodException,SecurityE
xception

Applet,AWT and JavaSwing Tutorial

How to get the object of class Class?


There are 3 ways to get the instance of
Class class. They are as follows:
forName() method of Class class
getClass() method of Object class
the .class syntax
1) forName() method of Class class
is used to load the class dynamically.
returns the instance of Class class.
It should be used if you know the fully
qualified name of class.This cannot be used
for primitive types
Applet,AWT and JavaSwing Tutorial

2) getClass() method of Object class


It returns the instance of Class class.
It should be used if you know the
type. Moreover, it can be used with
primitives.
3) The .class syntax
If a type is available but there is no
instance then it is possible to obtain
a Class by appending ".class" to the
name of the type.It can be used for
primitive data type also.
Applet,AWT and JavaSwing Tutorial

Determining the class object


Following methods of Class class is used to
determine the class object:
1) public boolean
isInterface():determines if the specified
Class object represents an interface
type.2) public boolean
isArray():determines if this Class object
represents an array class.3) public
boolean isPrimitive():determines if the
specified Class object represents a
primitive type.
Applet,AWT and JavaSwing Tutorial

Creating a program that works as


javap tool
Following methods
Method
Description can be
ofjava.lang.Classclass
public Field[]
returns an array of Field objects
used
to
display
the
metadata of a
getDeclaredFields()throws
reflecting all the fields declared by
SecurityException
the class or interface represented by
class.
this Class object.

public Constructor[]
getDeclaredConstructors()throws
SecurityException

returns an array of Constructor


objects reflecting all the constructors
declared by the class represented by
this Class object.

public Method[]
getDeclaredMethods()throws
SecurityException

returns an array of Method objects


reflecting all the methods declared
by the class or interface represented
by this Class object.

Applet,AWT and JavaSwing Tutorial

How to call private method from


another class in java
You can call the private method from
outside the class by changing the
runtime behaviour of the class.
By the help ofjava.lang.Classclass
andjava.lang.reflect.Methodclass
, we can call private method from
any other class.

Applet,AWT and JavaSwing Tutorial

Required methods of Method class


1) public void
setAccessible(boolean status)
throws SecurityExceptionsets the
accessibility of the method.
2) public Object invoke(Object
method, Object... args) throws
IllegalAccessException,
IllegalArgumentException,
InvocationTargetExceptionis used
to invoke the method.
Applet,AWT and JavaSwing Tutorial

10

Required method of Class class


1) public Method
getDeclaredMethod(String
name,Class[]
parameterTypes)throws
NoSuchMethodException,SecurityE
xception:returns a Method object that
reflects the specified declared method
of the class or interface represented by
this Class object.
Example of calling private method from
another class
Applet,AWT and JavaSwing Tutorial

11

newInstance() method
ThenewInstance()method
ofClassclass andConstructorclass is
used to create a new instance of the
class.
The newInstance() method of Class
class can invoke zero-argument
constructor whereas newInstance()
method of Constructor class can invoke
any number of arguments. So
Constructor class is preferred over
Class class.
Applet,AWT and JavaSwing Tutorial

12

Syntax of newInstance() method


of Class class
public T newInstance()throws
InstantiationException,IllegalAcc
essException
Here T is the generic version. You can
think it like Object class. You will
learn about generics later.

Applet,AWT and JavaSwing Tutorial

13

What is an applet?
An applet is a small Java program
that is embedded and ran in some
other Java interpreter program such
as
a Java technology-enabled browser
Suns applet viewer program called
appletviewer

Applet,AWT and JavaSwing


Tutorial

14

An applet program is a written


as a inheritanceof
thejava.Appletclass
There is no main()method in an
Applet.
An applet uses AWTfor graphics

Applet,AWT and JavaSwing


Tutorial

15

Life Cycle of an Applet:


init: This method is intended for whatever
initialization is needed for an applet.
start: This method is automatically called
after init method. It is also called
whenever user returns to the page
containing the applet after visiting other
pages.
stop: This method is automatically called
whenever the user moves away from the
page containing applets. This method can
be used to stop an animation.
destroy: This method is only called when
the browser shuts down normally.
Applet,AWT and JavaSwing
Tutorial

16

Introduction
Applet runs in the browser and its
lifecycle method are called by JVM when
it is loaded and destroyed. Here are the
lifecycle methods of an Applet:
init(): This method is called to
initialized an applet
start(): This method is called after
the initialization of the applet.
stop(): This method can be called
multiple times in the life cycle of an
Applet.
Applet,AWT and JavaSwing
Tutorial

17

destroy(): This method is called


only once in the life cycle of the
applet when applet is destroyed.

Applet,AWT and JavaSwing


Tutorial

18

init () method:The life cycle of an applet is


beginon that time when the applet is first
loaded into the browser and called the init()
method. The init() method is called only one time
in the life cycle on an applet. The init() method is
basically called to read the PARAM tag in the
html file. The init () method retrieve the passed
parameter through the PARAM tag of html file
using
get
Parameter()
method
All
the
initialization such as initialization of variables
and the objects like image, sound file are loaded
in the init () method .After the initialization of the
init() method user can interactwith the Applet
and mostly applet contains the init() method.
Applet,AWT and JavaSwing
Tutorial

19

Start () method:The start method of


an applet is called after the
initialization method init(). This
method may be called multiples time
when the Applet needs to be started
or restarted. For Example if the user
wants to return to the Applet, in this
situation the start Method() of an
Applet will be called by the web
browser and the user will be back on
the applet. In the start method user
can interact within the applet.
Applet,AWT and JavaSwing
Tutorial

20

Stop () method:The stop() method can


be called multiple times in the life cycle of
applet like the start () method. Or should
be called at least one time. There is only
miner difference between the start()
method and stop () method. For example
the stop() method is called by the web
browser on that time When the user
leaves one applet to go another applet
and the start() method is called on that
time when the user wants to go back into
the first program or Applet.
Applet,AWT and JavaSwing
Tutorial

21

destroy() method:The destroy()


method is called only one time in
the life cycle of Applet like init()
method. This method is called only
on that time when the browser needs
to Shut down.

Applet,AWT and JavaSwing


Tutorial

22

Introduction
Applet isjava programthat can be
embedded intoHTML pages. Java
applets runs on the java enables web
browsers such as mozila and internet
explorer. Applet is designed to run
remotely on the client browser, so
there are some restrictions on it.
Applet can't access system resources
on the local computer. Applets are
used to make the web site more
dynamic and entertaining.
Applet,AWT and JavaSwing
Tutorial

23

Advantages of Applet:
Applets are cross platform and can run on
Windows, Mac OS and Linux platform
Applets can work allthe version of Java Plugin
Appletsruns in a sandbox, so the user does
not need to trust the code, so it can work
without security approval
Applets are supported by most web browsers
Applets are cached in most web browsers, so
will be quick to load when returning to a web
page
User can also have full access to the machine
if user allows
Applet,AWT and JavaSwing
Tutorial

24

Disadvantages of Java Applet:


Java plug-in is required to run applet
Java appletrequires JVM so first time it
takes significant startup time
If applet is not already cached in the
machine, it will be downloaded from
internet and will take time
Its difficult to desing and build good
user interface in applets compared to
HTML technology

Applet,AWT and JavaSwing
Tutorial

25

Applet Vs Application
Applets as previously described,
are the small programs while
applications
are larger programs. Applets
don't have the main method
while in an application execution
starts with the main method.
Applets canrun in our browser's
window or in an appletviewer
Applet,AWT and JavaSwing
Tutorial

26

To run the applet in an appletviewer will be


an advantage for debugging. Applets are
designed for the client site programming
purpose while the applications don't have
such type of criteria.
Appletare thepowerful toolsbecause it
covers half ofthejavalanguage
picture.Java appletsare the best way of
creating theprograms in java. There are
a less number of java programmers that
have the hands on experience on java
applications.
Applet,AWT and JavaSwing
Tutorial

27

This is not the deficiency of java


applications but the global utilization
of internet. It doesn't mean that the
java applications don't have the
place. Both (Applets and the java
applications) have the same
importance at their own places.
Applications are also the platform
independent as well as byte oriented
just like the applets.

Applet,AWT and JavaSwing


Tutorial

28

Applets are designed just for handling


the client site problems. while the
java applications are designed to
work with the client as well as server.
Applications are designed to exists in
a secure area. while the applets are
typically used.

Applet,AWT and JavaSwing


Tutorial

29

Applications and applets have much of


the similarity such as both have most
of the same features and share the
same resources. Applets are created
by extending the java.applet.Applet
class while the java applications start
execution from the main method.

Applet,AWT and JavaSwing


Tutorial

30

Applications are not too small to


embed into a html page so that the
user can view the application in your
browser. On the otherhandapplet
have the accessibility criteria of the
resources. The key feature is that
while they have so many differences
but both can perform the same
purpose.

Applet,AWT and JavaSwing


Tutorial

31


One more thing to point here is that
applets are unable to use the native
methods,run any program on the
user system or load shared libraries.
The majorsecurityconcern here is
that the local shared libraries and the
native methods may results in the
loophole in the java security model.

Applet,AWT and JavaSwing


Tutorial

32

The major differencebetween the two


(applet and application) is that java
applications are designed to work
under the homogenous and more
secure areas. On contrary to that,
java applets are designed torun the
heterogeneous and
probablyunsecuredenvironment.
Internet has imposed several
restrictions on it.

Applet,AWT and JavaSwing


Tutorial

33

The applet is running and


rendered onthe web page.
Every Applet needs to implement
one or moreof the init(), the
start( ) and the paint( ) methods.
At the end of the execution, the
stop( ) method is invoked,
followed by the destroy( )
method to deallocate the
applets resources.
Applet,AWT and JavaSwing
Tutorial

34

Applet life cycle


browser visits page containing an applet
browser calls init on that applet, once
browser calls start on that applet
browser goes away from that page
browser calls stop on that applet
browser comes back to that page
browser calls start again on that applet
browser shuts down
browser calls destroy on the applet, once
Applet,AWT and JavaSwing
Tutorial

35

HTML tags for applets -1<APPLET


// the beginning of the HTML applet code
CODE="demoxx.class"
// the actual name of the applet (usually a 'class'
file)
CODEBASE="demos/"
// the location of the applet (relative as here, or
a full URL)
NAME=SWE622"
// the name of the instance of the appleton this
page
WIDTH="100"
// the physical width of the applet on the page
HEIGHT="50"
//the physical height of the applet on the page
ALIGN="Top"
// align the applet within its page space (top,
bottom, center)
Applet,AWT and JavaSwing
Tutorial

36

HTML tags for applets


-2<APPLETCODE=test.class"
CODEBASE="example/"
WIDTH=460
HEIGHT=160NAME="buddy"
><PARAMNAME="imageSource"
VALUE="images/Beans">
<PARAM
NAME="backgroundColor"
VALUE="0xc0c0c0"> <PARAM
NAME="endImage" VALUE=10>
</APPLET>
Applet,AWT and JavaSwing
Tutorial

37

Attribute

Explaination

Example

Code

Name of class file

Code=applet0.class

Width

Width of applet

Width=300

Height

Height of Applet

Height=300

Code base

Applets Directory

Codebase=/applet

Alt

Alternate text if the


Alt=menu applet
Applet is not available

Name

Name of the applet

Align(top,left,right,bot Justify applet with the


tom)
Text

Name=AppletExam
Align=right

Applet,AWT and JavaSwing


Tutorial

38

History of an Applet
Edit java source code & html
notepad Hello.java
notepad Hello.html
Compile source to ByteCodes
javacHello.java
produces Hello.class
View applet (Java Virtual Machine)
appletviewerHello.html
browser Hello.html
Applet,AWT and JavaSwing
Tutorial

39

<html>
<body>
<applet code=Hello.class
<width=300height=300>
</applet>
</body>
</html>
Save as Hello.html

Applet,AWT and JavaSwing


Tutorial

40

import java.applet.Applet;
import java.awt.*;
public class Hello extends Applet{
public void init() {
repaint();
}
public void paint(Graphics g) {
g.drawString(Hello World!,30,30);
}

}
Save as Hello.java
Applet,AWT and JavaSwing
Tutorial

41

History of an Applet
Edit java source code & html
notepad Hello.java
notepad Hello.html
Compile source to ByteCodes
javacHello.java
produces Hello.class
View applet (Java Virtual Machine)
appletviewerHello.html
browser Hello.html
Applet,AWT and JavaSwing
Tutorial

42

Applet Security
For security reasons, applets that are
loaded over the network have
severalrestrictions.
an appletcannotordinarily reador
writefiles on the computer that
it's executing on.
an applet cannotmakenetwork
connectionsexcept to the
hostthat it came from.
Applet,AWT and JavaSwing
Tutorial

43

What are the disadvantages of


applets?
Applets cant run any local
executable programs
Applets cant with any host other
than the originating server
Applets cant read/write to local
computers file system

Applet,AWT and JavaSwing


Tutorial

44

What are the disadvantages of


applets? (Contd)
Applets cant find any information
about the local computer
All java-created pop-up windows
carry a warning message
Stability depends on stability of the
clients web server
Performance directly depend on
clients machine
Applet,AWT and JavaSwing
Tutorial

45

What are the advantages of


applets?
Automatically integrated with HTML;
hence, resolved virtually all installation
issues.
Can be accessed from various platforms
and various java-enabled web browsers.
Can provide dynamic, graphics
capabilities and visualizations
Implemented in Java, an easy-to-learn
OO programming language
Applet,AWT and JavaSwing
Tutorial

46

What are the advantages of


applets? (Contd)
Alternative to HTML GUI design
Safe! Because of the security built
into the core Java language and the
applet structure, you dont have to
worry about bad code causing
damage to someones system
Can be launched as a standalone
web application independent of the
host web server
Applet,AWT and JavaSwing
Tutorial

47

Event Handling
Examining of Event Classes and
Interfaces
Events are Supported by
java.awt.event package
Event
Source
Listener
Applet,AWT and JavaSwing
Tutorial

48

Event Classes
MouseWheelevent
ActionEvent TextEvent
AdjustmentEvent WindowEvent
ComponentEvent
ContainerEvent
FocusEvent
InputEvent
ItemEvent
KeyEvent
MouseEvent
Applet,AWT and JavaSwing
Tutorial

49

Source of Events
Button
CheckBox
Choice
List
MenuItem
ScrollBar
TextComponents
Window
Applet,AWT and JavaSwing
Tutorial

50

EventListener Interface
ActionListener
AdjustmentListener
ComponentListener
ContainerListener
FocusListener
ItemListener
KeyListener
MouseListener
MouseMotionListener
Applet,AWT and JavaSwing
Tutorial

51

MouseWheelListener
TextListener
WindowListener
ActionListener Interface
void actionPerformed(ActionEvent ae)
AdjustmentListener interface
Void
adjustmentValueChanged(AdjustmentEv
ent ae)
Applet,AWT and JavaSwing
Tutorial

52

ComponentListener Interface
Void componentResized(ComponentEvent ce)
Void componentMoved(ComponentEvent ce)
Void componentShown(ComponentEvent ce)
Void componentHidden(ComponentEvent ce)
ContainerListener Interface
Void componentAdded(ContainerEvent ce)
Void componentRemoved(ContainerEvent ce)

Applet,AWT and JavaSwing


Tutorial

53

FocusListenerEvent Interface
Void FicusGained(FocusEvent fe)
Void focusLost(FocusEvent fe)
ItemListener Interface
Void ItemStateChanged (ItemEvent ie)
KeyListener Interface
Applet,AWT and JavaSwing
Tutorial

54

Void keyPressed(keyEvent ke)


Void keyReleased(keyEvent ke)
Void keyTyped(keyEvent ke)
MouseListener Interface
Void mouseClicked(MouseEvent me)
Void mouseEntered(MouseEvent me)
Void mouseExited(MouseEvent me)
Void mousepressed(MouseEvent me)
Void mouseReleased(MouseEvent me)
Applet,AWT and JavaSwing
Tutorial

55

MouseMotionListener Interface
Void mouseDragged(MouseEvent me)
Void mouseMoved(MouseEvent me)
TextListenerInterface
Void textChanged(TextEvent te)
WindowListener Interface
Void windowActivated(WindoEvent we)
Void windowClosed(WindoEvent we)
Applet,AWT and JavaSwing
Tutorial

56

Void windowClosing(WindoEvent we)


Void windowDeactivated(WindoEvent
we)
Void windowDeiconified(WindoEvent
we)
Void windowIconified(WindoEvent we)
Void windowOpened(WindoEvent we)

Applet,AWT and JavaSwing


Tutorial

57

Working with AWT Graphics


Drawing Lines
Void drawLine(int startX, int startY, int
endX, int endY);
Drawing Rectangles
Void drawRect(int top, int left, int width,
int height)
Void drawRoundRect(int top, int left, int
width, int height, int xDiam, int yDiam)
Applet,AWT and JavaSwing
Tutorial

58

Drawing Ellipses and Circles


Void drawOval(int top, int left, int
width, int height)
Void drawArc(int top, int left, int width,
int height, int startangle, int
sweepangle)
Void drawPolygon(int x[], int y[], int
numPoints)

Applet,AWT and JavaSwing


Tutorial

59

Working with Color


Color(int red, int green, int blue)
Setting Color
Void setColor(Color newColor)
Color getColor()

Applet,AWT and JavaSwing


Tutorial

60

Working with Fonts


Font class Methods
String getFamily()
Static Font getFont(String property)
String getFontName()
String getName()
Int getSize()
Boolean isItalic()
Boolean isPlain()
Boolean isBold()
Applet,AWT and JavaSwing
Tutorial

61

Font Matrices
Methods
Int charWidth(int c)
Int cahrWidth(char c)
Int getAscent()
Int getDescent()
Font getFont()
Int getHeight()
Int stringWidth(String str)
Applet,AWT and JavaSwing
Tutorial

62

AWT Control Fundamentals


Labels ---------------- Label()
PushButtons ----------Button()
Check Boxes----------Checkbox()
Choice Lists
Lists
Scroll Bars
Textfield
Textarea
Applet,AWT and JavaSwing
Tutorial

63

Layout Managers
FlowLayout()
BorderLayout()
GridLayout()
CardLayout()
Menu()
MenuItem()

Applet,AWT and JavaSwing


Tutorial

64

Java Swing
Japplet
Jbutton
JCheckbox
Jcombobox
Jlabel
Jradiobutton
Jscrollpane
Jtable
JTextField
JTree
Applet,AWT and JavaSwing
Tutorial

65

Applet,AWT and JavaSwing


Tutorial

66

Applet,AWT and JavaSwing


Tutorial

67

Applet,AWT and JavaSwing


Tutorial

68

Applet,AWT and JavaSwing


Tutorial

69

Applet,AWT and JavaSwing


Tutorial

70

Applet,AWT and JavaSwing


Tutorial

71

Applet,AWT and JavaSwing


Tutorial

72

Applet,AWT and JavaSwing


Tutorial

73

Applet,AWT and JavaSwing


Tutorial

74

Applet,AWT and JavaSwing


Tutorial

75

Applet,AWT and JavaSwing


Tutorial

76

Applet,AWT and JavaSwing


Tutorial

77

Applet,AWT and JavaSwing


Tutorial

78

Applet,AWT and JavaSwing


Tutorial

79

Applet,AWT and JavaSwing


Tutorial

80

Applet,AWT and JavaSwing


Tutorial

81

Applet,AWT and JavaSwing


Tutorial

82

Applet,AWT and JavaSwing


Tutorial

83

Applet,AWT and JavaSwing


Tutorial

84

Applet,AWT and JavaSwing


Tutorial

85

Applet,AWT and JavaSwing


Tutorial

86

Applet,AWT and JavaSwing


Tutorial

87

Applet,AWT and JavaSwing


Tutorial

88

Applet,AWT and JavaSwing


Tutorial

89

Applet,AWT and JavaSwing


Tutorial

90

Applet,AWT and JavaSwing


Tutorial

91

Applet,AWT and JavaSwing


Tutorial

92

Applet,AWT and JavaSwing


Tutorial

93

Applet,AWT and JavaSwing


Tutorial

94

Applet,AWT and JavaSwing


Tutorial

95

Applet,AWT and JavaSwing


Tutorial

96

Applet,AWT and JavaSwing


Tutorial

97

Applet,AWT and JavaSwing


Tutorial

98

Applet,AWT and JavaSwing


Tutorial

99

Applet,AWT and JavaSwing


Tutorial

100

Applet,AWT and JavaSwing


Tutorial

101

Applet,AWT and JavaSwing


Tutorial

102

Applet,AWT and JavaSwing


Tutorial

103

Applet,AWT and JavaSwing


Tutorial

104

Applet,AWT and JavaSwing


Tutorial

105

Applet,AWT and JavaSwing


Tutorial

106

Applet,AWT and JavaSwing


Tutorial

107

Applet,AWT and JavaSwing


Tutorial

108

Applet,AWT and JavaSwing


Tutorial

109

Applet,AWT and JavaSwing


Tutorial

110

Applet,AWT and JavaSwing


Tutorial

111

Applet,AWT and JavaSwing


Tutorial

112

Applet,AWT and JavaSwing


Tutorial

113

Applet,AWT and JavaSwing


Tutorial

114

Applet,AWT and JavaSwing


Tutorial

115

Applet,AWT and JavaSwing


Tutorial

116

Applet,AWT and JavaSwing


Tutorial

117

Applet,AWT and JavaSwing


Tutorial

118

Applet,AWT and JavaSwing


Tutorial

119

Applet,AWT and JavaSwing


Tutorial

120

Applet,AWT and JavaSwing


Tutorial

121

Applet,AWT and JavaSwing


Tutorial

122

Applet,AWT and JavaSwing


Tutorial

123

Applet,AWT and JavaSwing


Tutorial

124

Applet,AWT and JavaSwing


Tutorial

125

Applet,AWT and JavaSwing


Tutorial

126

Applet,AWT and JavaSwing


Tutorial

127

Vous aimerez peut-être aussi