Java is an OOP language and it is not a pure Object Based Programming Language
Many languages are Object Oriented. There are seven qualities to be satisfied for a programming language to be pure Object Oriented. They are:
1.Encapsulation/Data Hiding – Declaring public, private, protected access specifiers for methods and variables.
2.Inheritance- Using extends keyword in classes
3.Polymorphism – Using overloading and overriding
4.Abstraction- Using Interfaces
5.All predefined types are objects- Java API classes
6.All operations are performed by sending messages to objects
7.All user defined types are objects.
JAVA is not because it supports Primitive datatype such as int, byte, long... etc, to be used, which are not objects.Contrast with a pure OOP language like Smalltalk, where there are no primitive types,and boolean, int and methods are all objects.
Wednesday, October 14, 2009
Types and Uses of Reflection
Types of Reflections
There are generally two types of reflection
1) Introspection
2) Intercession
In Introspection we can see the features of a class or object of our interest using the methods available. Java just supports introspection C++ doesn't even support this maybe very remotely.
In Intercession we are actually able to make changes in the class i.e. we not only can see but also can modify what we see. Java doesn't support it. Open Java OpenC++
are some technologies which give us some intercession facilities.
Advantages of Reflections
1) Reflections are basically used to find the details of a class based on the object.
2) Reflection allows an executing Java program to examine or introspect upon itself and manipulate internal properties of the program. For example it's possible for a Java class to obtain the names of all its members and display them.
3) Reflection is also used in JavaBeans to set the property values from the request object.
4) Extensibility Features: An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.
5) Class Browsers and Visual Development Environments: A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.
6) Debuggers and Test Tools: Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.
Disadvantages of Reflection
a) Performance Overhead: Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
b) Security Restrictions: Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.
c) Exposure of Internals: Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.
Example:-
public class Main {
public static void main(String[] args) throws Exception
{
doRegular();
doReflection();
}
public static void doRegular() throws Exception
{
long start = System.currentTimeMillis();
for (int i=0; i<1000000; i++)
{
A a = new A();
}
System.out.println(System.currentTimeMillis() - start);
}
public static void doReflection() throws Exception
{
long start = System.currentTimeMillis();
for (int i=0; i<1000000; i++)
{
A a = (A) Class.forName("misc.A").newInstance();
}
System.out.println(System.currentTimeMillis() - start);
}
}
There are generally two types of reflection
1) Introspection
2) Intercession
In Introspection we can see the features of a class or object of our interest using the methods available. Java just supports introspection C++ doesn't even support this maybe very remotely.
In Intercession we are actually able to make changes in the class i.e. we not only can see but also can modify what we see. Java doesn't support it. Open Java OpenC++
are some technologies which give us some intercession facilities.
Advantages of Reflections
1) Reflections are basically used to find the details of a class based on the object.
2) Reflection allows an executing Java program to examine or introspect upon itself and manipulate internal properties of the program. For example it's possible for a Java class to obtain the names of all its members and display them.
3) Reflection is also used in JavaBeans to set the property values from the request object.
4) Extensibility Features: An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.
5) Class Browsers and Visual Development Environments: A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.
6) Debuggers and Test Tools: Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.
Disadvantages of Reflection
a) Performance Overhead: Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
b) Security Restrictions: Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.
c) Exposure of Internals: Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.
Example:-
public class Main {
public static void main(String[] args) throws Exception
{
doRegular();
doReflection();
}
public static void doRegular() throws Exception
{
long start = System.currentTimeMillis();
for (int i=0; i<1000000; i++)
{
A a = new A();
}
System.out.println(System.currentTimeMillis() - start);
}
public static void doReflection() throws Exception
{
long start = System.currentTimeMillis();
for (int i=0; i<1000000; i++)
{
A a = (A) Class.forName("misc.A").newInstance();
}
System.out.println(System.currentTimeMillis() - start);
}
}
Labels:
Reflections in Java
Reflections in Java
Reflection is a powerful approach to analyze the class at runtime. If new classes are added into your application dynamically then Reflection is used to get the structure of the class. Reflection uses special kind of java class: Class. The object of the Class type can hold all the information of the class and have getter methods to extract this information.
Example on Reflection:
By changing the class in the above example we can get different properties of the class it is using. In the below example we are using String class.
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) {
try {
// Creates an object of type Class which contains the information of the class String
Class cl = Class.forName("java.lang.String");
// getDeclaredFields() returns all the constructors of the class.
Constructor cnst[] = cl.getConstructors();
// getFields() returns all the declared fields of the class.
Field fld[] = cl.getDeclaredFields();
// getMethods() returns all the declared methods of the class.
Method mtd[] = cl.getMethods();
System.out.println("Name of the Constructors of the String class" );
for (int i = 0; i < cnst.length; i++) {
System.out.println(cnst[i].getName());
}
System.out.println("Name of the Declared fields");
for (int i = 0; i < fld.length; i++) {
System.out.println(fld[i].getName());
}
System.out.println("Name of the Methods");
for (int i = 0; i < mtd.length; i++) {
System.out.println(mtd[i].getName());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Example on Reflection:
By changing the class in the above example we can get different properties of the class it is using. In the below example we are using String class.
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) {
try {
// Creates an object of type Class which contains the information of the class String
Class cl = Class.forName("java.lang.String");
// getDeclaredFields() returns all the constructors of the class.
Constructor cnst[] = cl.getConstructors();
// getFields() returns all the declared fields of the class.
Field fld[] = cl.getDeclaredFields();
// getMethods() returns all the declared methods of the class.
Method mtd[] = cl.getMethods();
System.out.println("Name of the Constructors of the String class" );
for (int i = 0; i < cnst.length; i++) {
System.out.println(cnst[i].getName());
}
System.out.println("Name of the Declared fields");
for (int i = 0; i < fld.length; i++) {
System.out.println(fld[i].getName());
}
System.out.println("Name of the Methods");
for (int i = 0; i < mtd.length; i++) {
System.out.println(mtd[i].getName());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Labels:
Reflections in Java
List of Type Conversions
Some of the Type Casts which are used frequently in applications are as follows
Integer to String
int i = 10;
String str = Integer.toString(i);
(or)
String str = “”+i;
double to String
String str = Double.toString(i);
long to String
String str = Long.toString(l);
float to String
String str = Float.toString(f);
String to integer
str = "25";
int i = Integer.valueOf(str).intValue();
(or)
int i = Integer.parseInt(str);
String to double
Double d = Double.valueOf(str).doubleValue();
String to long
long l = Long.valueOf(str).longValue();
(or)
Long l = Long.parseLong(str);
String to float
Float f = Float.valueOf(str).floatValue();
Integer to boolean
b = (i != 0);
// ex : 42 != 0 --> true
Boolean to integer
i = (b)?1:0;
// true --> 1
All the type conversions must catch in NumberFormatException.
Integer to String
int i = 10;
String str = Integer.toString(i);
(or)
String str = “”+i;
double to String
String str = Double.toString(i);
long to String
String str = Long.toString(l);
float to String
String str = Float.toString(f);
String to integer
str = "25";
int i = Integer.valueOf(str).intValue();
(or)
int i = Integer.parseInt(str);
String to double
Double d = Double.valueOf(str).doubleValue();
String to long
long l = Long.valueOf(str).longValue();
(or)
Long l = Long.parseLong(str);
String to float
Float f = Float.valueOf(str).floatValue();
Integer to boolean
b = (i != 0);
// ex : 42 != 0 --> true
Boolean to integer
i = (b)?1:0;
// true --> 1
All the type conversions must catch in NumberFormatException.
Labels:
Type Conversions
Java Type Conversions
There are two types of java data type conversions
1)Automatic Conversion: In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:
byte -> short -> int -> long -> float -> double
Example:
// 64 bit long integer
long myLongInteger;
// 32 bit standard integer
int myInteger;
The extra storage associated with the long integer, in the above example, will simply be padded with extra zeros.
2) Explicit Conversion: The above will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion (assuming of course that the long integer will fit into a standard integer). This is done using a process known as a type cast.
Example:
myInteger = (int) myLongInteger
This tells the compiler that the type of myLongInteger must be temporarily changed to a int when the given assignment statement is processed. Thus, the cast only lasts for the duration of the assignment.
Java type casts have the following form:
(T) N
where T is the name of a numeric type and N is a data item of another numeric type. The result is of type T.
1)Automatic Conversion: In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:
byte -> short -> int -> long -> float -> double
Example:
// 64 bit long integer
long myLongInteger;
// 32 bit standard integer
int myInteger;
The extra storage associated with the long integer, in the above example, will simply be padded with extra zeros.
2) Explicit Conversion: The above will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion (assuming of course that the long integer will fit into a standard integer). This is done using a process known as a type cast.
Example:
myInteger = (int) myLongInteger
This tells the compiler that the type of myLongInteger must be temporarily changed to a int when the given assignment statement is processed. Thus, the cast only lasts for the duration of the assignment.
Java type casts have the following form:
(T) N
where T is the name of a numeric type and N is a data item of another numeric type. The result is of type T.
Labels:
Type Conversions
Thursday, September 17, 2009
Ajax Example
Index.jsp : Following is the JSP file where the Ajax code is included.
var objXMLHTTP = null; // JavaScript variable of xmlHttp object.
function GetXmlHttpObject() {
var objXMLHttp=null
if (window.XMLHttpRequest) // For Non-IE Browsers
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject) // For IE
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}
function searchData(){
//document.getElementById('courseTitle').outerHTML = 'loading..';
objXMLHTTP=GetXmlHttpObject();
if (objXMLHTTP==null){
alert ("Browser does not support HTTP Request");
return;
}
var url = "<%=request.getContextPath()%>/AjaxServlet";
objXMLHTTP.onreadystatechange=setPageData;
objXMLHTTP.open("POST",url,true);
objXMLHTTP.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
objXMLHTTP.send(null);
}
function setPageData(){
try {
if (objXMLHTTP.readyState == 4)
{
if (objXMLHTTP.status == 200)
{
var resultXML = objXMLHTTP.responseXML;
var cCity = resultXML.getElementsByTagName('city');
var cEmailId = resultXML.getElementsByTagName('emailId');
document.f.city.value = cCity[0].childNodes[0].nodeValue;
document.f.emailId.value = cEmailId[0].childNodes[0].nodeValue;
}
}
}
catch(err)
{
alert("Problem with server response:\n "+ objXMLHTTP.statusText);
}
} Servlet: Following is the method in AjaxServlet file which send the response.
AjaxServlet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/xml");
PrintWriter out = response.getWriter();
try {
StringBuffer sb = new StringBuffer();
sb.append("");
sb.append("");
sb.append("Hyderabad");
sb.append(" ");
sb.append("");
sb.append("k.ravichandra@yahoo.com");
sb.append(" ");
sb.append(" ");
out.write(sb.toString());
} finally {
out.close();
}
}
var objXMLHTTP = null; // JavaScript variable of xmlHttp object.
function GetXmlHttpObject() {
var objXMLHttp=null
if (window.XMLHttpRequest) // For Non-IE Browsers
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject) // For IE
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}
function searchData(){
//document.getElementById('courseTitle').outerHTML = 'loading..';
objXMLHTTP=GetXmlHttpObject();
if (objXMLHTTP==null){
alert ("Browser does not support HTTP Request");
return;
}
var url = "<%=request.getContextPath()%>/AjaxServlet";
objXMLHTTP.onreadystatechange=setPageData;
objXMLHTTP.open("POST",url,true);
objXMLHTTP.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
objXMLHTTP.send(null);
}
function setPageData(){
try {
if (objXMLHTTP.readyState == 4)
{
if (objXMLHTTP.status == 200)
{
var resultXML = objXMLHTTP.responseXML;
var cCity = resultXML.getElementsByTagName('city');
var cEmailId = resultXML.getElementsByTagName('emailId');
document.f.city.value = cCity[0].childNodes[0].nodeValue;
document.f.emailId.value = cEmailId[0].childNodes[0].nodeValue;
}
}
}
catch(err)
{
alert("Problem with server response:\n "+ objXMLHTTP.statusText);
}
} Servlet: Following is the method in AjaxServlet file which send the response.
AjaxServlet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/xml");
PrintWriter out = response.getWriter();
try {
StringBuffer sb = new StringBuffer();
sb.append("
sb.append("
sb.append("Hyderabad");
sb.append("
sb.append("
sb.append("k.ravichandra@yahoo.com");
sb.append("
sb.append("
out.write(sb.toString());
} finally {
out.close();
}
}
Labels:
Ajax
Ajax Basics
Ajax stands for Asynchronous JavaScript and XML. Ajax is used to fetch the data from web server without refreshing the whole page. Ajax plays a major role in developing fast, interactive, dynamic and responsive site and can run on various operating systems, computer architectures and browsers. Its asynchronous characteristics have made it popular among the users to develop their site using Ajax.
Before commencing the name ‘Ajax’, it was being used as a name of XMLHTTTP in the programming that was inspired by the earlier one with a nearby similar concept XMLhttpRequest. In the earlier version of Internet Explorer (up to 4.0), a class XMLHttpRequest had been used in JavaScript to make IE browser that was later implemented in the modified form by various web masters to make their own web applications. Google has contributed most to its prominence by implementing XMLHTTP in Gmail and GoogleMaps in 2005.
But the true popularity bursts when XMLHTTP has got its present name ‘Ajax’. The ‘term’ was first used at February 18, 2005 in the web world by Jesse James Garret in his essay called “Ajax: A New Approach to Web Applications”.
Asynchronous server communication using XMLHttpRequest
XMLHttpRequest: - XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page's Client-Side and Server-Side.
XMLHttpRequest Methods:-
a) abort()
Cancels the current request.
b) getAllResponseHeaders()
Returns the complete set of HTTP headers as a string.
c) getResponseHeader( headerName )
Returns the value of the specified HTTP header.
open( method, URL )
open( method, URL, async )
open( method, URL, async, userName )
open( method, URL, async, userName, password )
Specifies the method, URL, and other optional attributes of a request.
The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such as "PUT" and "DELETE" (primarily used in REST applications), may be possible
The "async" parameter specifies whether the request should be handled asynchronously or not . "true" means that script processing carries on after the send() method, without waiting for a response, and "false" means that the script waits for a response before continuing script processing.
d) send( content )
Sends the request.
e) setRequestHeader( label, value )
Adds a label/value pair to the HTTP header to be sent.
XMLHttpRequest Properties:-
a) onreadystatechange
An event handler for an event that fires at every state change.
b) readyState
The readyState property defines the current state of the XMLHttpRequest object.
Here are the possible values for the readyState propery:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is completed
readyState=0 after you have created the XMLHttpRequest object, but before you have called the open() method.
readyState=1 after you have called the open() method, but before you have called send().
readyState=2 after you have called send().
readyState=3 after the browser has established a communication with the server, but before the server has completed the response.
readyState=4 after the request has been completed, and the response data have been completely received from the server.
c)responseText
Returns the response as a string.
d)responseXML
Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties.
e)status
Returns the status as a number (e.g. 404 for "Not Found" and 200 for "OK").
f)statusText
Returns the status as a string (e.g. "Not Found" or "OK").
Before commencing the name ‘Ajax’, it was being used as a name of XMLHTTTP in the programming that was inspired by the earlier one with a nearby similar concept XMLhttpRequest. In the earlier version of Internet Explorer (up to 4.0), a class XMLHttpRequest had been used in JavaScript to make IE browser that was later implemented in the modified form by various web masters to make their own web applications. Google has contributed most to its prominence by implementing XMLHTTP in Gmail and GoogleMaps in 2005.
But the true popularity bursts when XMLHTTP has got its present name ‘Ajax’. The ‘term’ was first used at February 18, 2005 in the web world by Jesse James Garret in his essay called “Ajax: A New Approach to Web Applications”.
Asynchronous server communication using XMLHttpRequest
XMLHttpRequest: - XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page's Client-Side and Server-Side.
XMLHttpRequest Methods:-
a) abort()
Cancels the current request.
b) getAllResponseHeaders()
Returns the complete set of HTTP headers as a string.
c) getResponseHeader( headerName )
Returns the value of the specified HTTP header.
open( method, URL )
open( method, URL, async )
open( method, URL, async, userName )
open( method, URL, async, userName, password )
Specifies the method, URL, and other optional attributes of a request.
The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such as "PUT" and "DELETE" (primarily used in REST applications), may be possible
The "async" parameter specifies whether the request should be handled asynchronously or not . "true" means that script processing carries on after the send() method, without waiting for a response, and "false" means that the script waits for a response before continuing script processing.
d) send( content )
Sends the request.
e) setRequestHeader( label, value )
Adds a label/value pair to the HTTP header to be sent.
XMLHttpRequest Properties:-
a) onreadystatechange
An event handler for an event that fires at every state change.
b) readyState
The readyState property defines the current state of the XMLHttpRequest object.
Here are the possible values for the readyState propery:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is completed
readyState=0 after you have created the XMLHttpRequest object, but before you have called the open() method.
readyState=1 after you have called the open() method, but before you have called send().
readyState=2 after you have called send().
readyState=3 after the browser has established a communication with the server, but before the server has completed the response.
readyState=4 after the request has been completed, and the response data have been completely received from the server.
c)responseText
Returns the response as a string.
d)responseXML
Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties.
e)status
Returns the status as a number (e.g. 404 for "Not Found" and 200 for "OK").
f)statusText
Returns the status as a string (e.g. "Not Found" or "OK").
Labels:
Ajax
Subscribe to:
Posts (Atom)