20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
1
Introduction to Java for Introduction to Java for CS381, EE4.WebCS381, EE4.Web
By Sifei [email protected] of ComputingSchool of EPSFebruary 2004
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
2
BeansBeans
• Baked haricot beans, typically cooked in tomato sauce and tinned?
• An edible seed growing in long pods on certain plants.
• The hard seed of a coffee or cocoa plant.
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
3
Java BeanJava Bean
• “A Java Bean is a reusable software component that can be manipulated visually in a builder tool”
Sun Microsystems
• Sun’s tutorial on Java Beanshttp://java.sun.com/docs/books/tutorial/javabeans
• Package: java.beans
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
4
ComponentsComponents
• Components are self-contained, reusable software units that can be visually composed into composite components, applets, applications, and servlets using visual application builder tools.
• JavaBean components are known as Beans.
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
5
JavaBeans, a component modelJavaBeans, a component model
• JavaBeans is Java’s component model• The model is made up of an architecture
and an API• The API makes it possible to write
component software in Java• The architecture provides the framework
(services and rules) that allows components to participate properly
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
6
Some DistinctionsSome Distinctions
• Features that distinguish a Java Bean from Java objects are:– Support for introspection– Support for customization– Support for events– Support for properties– Support for persistence
• Bean requires a zero-argument constructor.• Bean does not have public member variables.
– Access through pre-defined methods
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
7
Sources of Builder ToolsSources of Builder Tools
• Bean Builder from Sun:– http://java.sun.com/products/javabeans/beanbuilder/
• NetBeans:– http://www.netbeans.org
• JBuilder:– http://www.borland.com/jbuilder/
• Note, you also need to have the Java SDK installed.
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
8
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
9
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
10
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
11
Bean BooksBean Books
Developing Java Beans
Robert Englander
O’Reilly Recommended
JavaBeans Programming
J. O’Neil and
H. Schildt
McGraw Hill Good. Contains many examples.
JavaBeans by Example
Henri Jubin Prentice Hall Simpler than the above, but with useful examples
NetBeans – the Definitive Guide
Boudreau, Glick, Greene, Spurlin, Woehr
O’Reilly Not so good on Beans. More about the IDE.
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
12
The Component ModelThe Component Model
• Discovery and Registration
• Raising and Handling of Events
• Persistence
• Visual Presentation
• Support for Visual Programming
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
13
The Component ModelThe Component Model
• Raising and Handling of Events
– Beans (or JavaBeans components) use events to communicate with other Beans
– A Bean that wants to receive events (a listener Bean) registers its interest with the Bean that triggers the event (a source Bean)
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
14
The Component ModelThe Component Model
• Persistence
– Persistence enables Beans to save and restore their state
– JavaBeans uses Java Object Serialization to support persistence
– implements java.io.Serializable
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
15
The Component ModelThe Component Model
• Visual Presentation
– The Bean is free to choose its own visual presentation (fonts, colours, shape, etc)
– Many of these characteristics will be properties of the Bean (some might be persistent too)
• Note: Not all beans are visual beans. Beans need not to be visual !
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
16
The Component ModelThe Component Model
• Support of Visual Programming
– User can select a component from the toolbox and place it into a container
– Properties of the component can then be edited to create the desired behaviour
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
17
Properties, Methods & EventsProperties, Methods & Events
• A property is a subset of a component’s state.– Allow the user to control the behavior of that
component so it operates as desired.
• Methods can be invoked to execute code in a component.
• An event is a notification that is generated by a component when there is some change in its state.
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
18
PropertiesProperties
• Named attributes that can be read or set by other beans
• Accessibility of a bean’s properties is only via its get and set methods
• In the Java Beans model, properties will only be recognised if appropriate get and (or) set methods are defined– not necessarily both
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
19
A Pepper BeanA Pepper Beanpublic class Pepper { private String iKind; private int iHeatLevel;
public Pepper( ) { }
public String getKind( ) { return iKind; } public void setKind(String aKind) { iKind = aKind; }}
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
20
Introspection and PropertiesIntrospection and Properties• The process by which builder tools discover a Bean’s
features.• By following specific naming conventions, the properties
of a Bean that are “revealed” to the world can be identified:
public class SignalGenerator {private double frequency;// … constructor methods herepublic double getFrequency( ) { return frequency; }
public void setFrequency(double frequency) { this.frequency = frequency;}
}
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
21
Conventions for Access MethodsConventions for Access Methods• Simple Properties:
– For a property of type Type and name Name:– public Type getName( );– public void setName(Type value);
• Boolean Properties:– public boolean isName( );– public void setName(boolean value);– public boolean getName();
• Indexed Properties:– public Type getName(int index);– public Type[] getName();– public void setName(int index, Type value);– public void setName(Type values[]);
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
22
MethodsMethods
• A Bean may be implemented by a Java Class
• That Class contains a number of methods that may be used to access and control the component
• These are generally all the public methods of the Class that implements the Bean
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
23
EventsEvents
• JavaBeans components interact by generating “Events”• Several components may register an interest in an Event that
is generated by a specific component• Occurrence of the Event triggers methods to be called in all
the components that are “listening” for it• public void add<ListenerType>(<ListenerType> listener);• public void remove<ListenerType>(<ListenerType>
listener);
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
24
QuoteLog
Graph
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
25
Reacting to ChangeReacting to Change
• In general, a change in the value of a property of a bean will trigger some activity
• Could code this directly into the get and set methods, but this “hard-wires” application specific dependencies into the methods
• More flexible (improving reusability) if events are generated when the properties are accessed
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
26
e.g. setting Kinde.g. setting Kindpublic void setKind(String aKind)
throws java.lang.Exception {if( aKind == “Strawberry” ) {
Exception ex = new Exception(“Not a chili pepper!”);
throw ex;}else
iKind = aKind;}
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
27
Application CodeApplication Code
Pepper pepper = new Pepper( );try {
pepper.setKind(“Strawberry”);}catch (Exception ex) {
System.out.println(“Exception - message is: ”+
ex.getMessage( ) };}
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
28
IntrospectionIntrospection
• The process by which builder tools discover a Bean’s features.
Beans support introspection in two ways:Beans support introspection in two ways: By adhering to specific rules (By adhering to specific rules (design patternsdesign patterns) )
when naming properties, methods and eventswhen naming properties, methods and events By explicitly providing property, method and By explicitly providing property, method and
event info within a event info within a Bean InformationBean Information class class
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
29
IntrospectionIntrospection
• Low-level reflection:– Follow Bean coding style (we have seen)– Analysis of the Bean’s class can then
reveal properties and methods
• Revealing complex properties:– Implement a “BeanInfo” class
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
30
IntrospectionIntrospection
• But the used within a visual development tool, a Bean must expose its:– properties,– methods– events
• Java reflection mechanism may not be sufficient
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
31
The BeanInfo InterfaceThe BeanInfo Interface
• Sometimes use of the design patterns:– reveals insufficient information– reveals to much information– forces inappropriate design choices
• Sometimes the information we wish to expose cannot be represented by a design pattern– e.g. choice of a graphic icon to represent the
Bean on a toolbar in a visual development tool
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
32
java.beans.BeanInfojava.beans.BeanInfoMethod Description
getAdditionalBeanInfo( ) Returns any additional BeanInfo objects that are relevant
getBeanDescriptor( ) Returns the Bean descriptor object
getDefaultEventIndex( ) Returns the default event index
getDefaultPropertyIndex( ) Returns the default property index
getEventSetDescriptors( ) Returns the event set descriptors
getIcon( ) Returns the specified icon for the Bean
getMethodDescriptors( ) Returns the method descriptors
getPropertyDescriptors( ) Returns the property descriptors
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
33
Implementing Implementing BeanInfoBeanInfo
• You do not have to provide a detailed implementation
• If any of the methods in the interface returns null, then low-level reflection will be used to gather all the information that is available
• If a non-null value is returned, then that is all the information on that aspect that is made available
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
34
Hiding InformationHiding Informationpublic class Pepper implements java.io.Serializable { private String iKind; private int iHeatLevel; public Pepper() {} public String getKind() { return iKind; } public void setKind(String aKind) { iKind = aKind; } public int getHeatLevel() { return iHeatLevel; } public void setHeatLevel(int aHeatLevel) { iHeatLevel = aHeatLevel; }}
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
35
PepperBeanInfo.javaPepperBeanInfo.java
import java.beans.*;import java.beans.SimpleBeanInfo; public class PepperBeanInfo extends SimpleBeanInfo { public PropertyDescriptor[] getPropertyDescriptors() { PropertyDescriptor[] pdArray = new PropertyDescriptor[1]; try { pdArray[0] = new PropertyDescriptor("heatLevel", Pepper.class); } catch (IntrospectionException e) { System.out.println("Error creating a PropertyDescriptor"); } return pdArray; }}
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
36
ExplanationExplanation
• SimpleBeanInfo implements BeanInfo• It contains default implementations that
return null• Inheriting the default implementation tells the
caller to use reflection• Overriding the default implementation
enables the developer to hide information by only providing descriptors for those features they wish to expose
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
37
Reflection vs. IntrospectionReflection vs. Introspection
• Reflection analyses the Bean itself to discover properties, methods and events
• Introspection relies (mostly) on the presence of a “meta-object” to provide information about the Bean (an instance of a BeanInfo class)
• What are the benefits of Introspection?
• What are the weaknesses?
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
38
IntrospectorIntrospector
• java.beans.Introspector– seeks a BeanInfo for a Bean– if any descriptors in BeanInfo return null, then use
reflection– if no BeanInfo, then use reflection
• The application always receives a BeanInfo object from the Introspector– (unless an exception occurs)
• The Introspector also “introspects” superclasses
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
39
CustomisationCustomisation
• Simple properties– Development tool will build property sheets
dynamically– User may then edit the properties to customise
the Bean
• For the Advanced User– Create a specific customiser for a Bean– This is kept separate to the Bean Class, as with
a BeanInfo Class
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
40
Further FeaturesFurther Features
• Visibility
– It is not necessary for a Bean to be visible at run-time (e.g. Bean controlling access to a device or data feed)
– It is necessary however for a Bean to support the visual builder tool. Even an ‘invisible’ run-time Bean shall be shown on the builder tool
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
41
Further FeaturesFurther Features
• Multithreading
– Always assume your code will be used in a multithreaded environment
– Make sure that your Beans are thread-safe– Multithreading in JavaBeans is no different
than multithreading in Java
20 February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
42
Further FeaturesFurther Features
• Security
– By default assume that your Beans are running in a non-trusted applet
– Apply security restrictions such as• Allow no access to the local file system
• Limit socket connections to the host system