CoreJava Important Tricks | Tips | Java Linux IDE | Technology Updates | Download Free CoreJava Examples | Video Tuorials | Concepts of Classes

Monday, January 19, 2009

Compiler Class

The java.lang.Compiler class provides a way to access an embedded Java compiler, which is loaded at startup if the java.compiler system property is defined.


The value of the property should be the name of a dynamically linked library implementing the compiler.


There is no predefined compiler; you must provide one.

Runtime Class

You can't construct a Runtime instance yourself. A Runtime object is obtained by calling the static method Runtime.getRuntime(). By using a Runtime instance, you can

  • Execute a subprocess.
  • Exit the program.
  • Load a dynamically linked library.
  • Run the garbage collector or finalize objects.
  • Estimate free memory.
  • Control program tracing.
  • Localize streams (make them translate from Unicode to the local character set).


A Runtime object can be used to execute another system process by way of the exec() method (in four flavors) that returns a java.lang.Process object.


The Process instance is useful for attaching to the standard input, output, and error streams of the new process.


You can also kill the subprocess, wait for it to terminate, and retrieve its exit code, all by way of the Process object.


The process exists outside the Java virtual machine. It is not a Thread but a separate system process, and some aspects of its behavior may be system-dependent.


You can use a Runtime object to load a dynamically linked library. This is necessary in order to use native methods in Java.


The methods traceInstructions() and traceMethodCalls() request that the Java virtual machine print trace information about each instruction or each method call that gets executed, respectively. Where the output ends up or whether tracing is supported at all is implementation-dependent.


While you can use a Runtime object to run the garbage collector or finalize any outstanding objects (gc() and runFinalization() methods), this should not normally be necessary, since the Java environment runs a separate thread whose purpose is to finalize and garbage collect when necessary.


Furthermore, although the exit() method can be used to exit the program, it should normally be avoided, except to specify an exit code upon normal termination of a stand-alone program. Low-level methods and applets generally throw exceptions instead.

System Class

There are no instances of the System class. The System class allows you to

  • Access the standard input, output, and error streams.
  • Exit the program.
  • Load a dynamically linked library.
  • Run the garbage collector or finalize objects.
  • Access system Properties.
  • Access the SecurityManager.
  • Perform system-dependent array copy and time-check operations.


The standard input, output, and error streams of your Java application or applet are accessed as System.in, System.out, and System.err.


These class variables are PrintStream objects (see java.io, below), allowing your application to perform the usual UNIX-style I/O.That's not much use in a finished applet, since an applet embedded in a web page is typically disallowed from doing anything useful with these streams. They are handy for debugging in appletviewer, and also in stand-alone Java applications.


Java also maintains some system properties, accessible through the System class. These take the place of environment variables and anything else in the system that is relevant to the Java environment.


The static method getProperties() returns a java.util.Properties object describing the system properties. For example, the properties can be listed by a little program such as the following:

public class Props
{
public static void main( String args[] )
{
System.getProperties().list(System.err);
}
}

This program results in a list of system properties:

-- listing properties --
java.home=/mnt2/java
java.version=1.0
file.separator=/
line.separator=

java.vendor=Sun Microsystems Inc.
user.name=korpen
os.arch=sparc
os.name=Solaris
java.vendor.url=http://www.sun.com/
user.dir=/nfs/grad/korpen/www/java
java.class.path=.:/home/grad/korpen/www/java:/mnt2/ja...
java.class.version=45.3
os.version=2.x
path.separator=:
user.home=/homes/ritesh

Use the static method getProperty() to get individual properties by name.

Cloning Objects | Cloneable Interface

the Cloneable Interface

Besides overriding the clone() method in java.lang.Object, a class may implement the interface Cloneable to indicate that it makes sense to clone this type of object.


The interface is an empty one.


You don't need to supply any methods to conform to Cloneable, although you may want to override the default clone() method.


Other classes can tell whether a class implements Cloneable by examining its class descriptor (an instance of the class Class).

Security Manager

By extending the abstract class java.lang.SecurityManager, you can specify a security policy for the current Java program.


Any code loaded over the Internet by your program is then subject to that policy, for example.


A Java program has only one SecurityManager. You can look up the current SecurityManager by calling System.getSecurityManager(). This method returns null to indicate that the default security policy is being used.


The default policy is rather lax. However, you can install a custom security manager. This allows you to do the following, among other things:

  • Prevent Java code from deleting, writing, or reading certain files.
  • Monitor or disallow certain socket connections.
  • Control which Threads may access which other Threads or ThreadGroups.
  • Control access to packages, and to system properties.


For example, the method call that checks whether the calling code is allowed to delete a certain file is declared:

public void checkDelete( String file );

The method must either return quietly, or throw a SecurityException. This is typical of the public methods in class SecurityManager.


To provide a custom security manager, write a subclass of SecurityManager and override some of its check methods. Although the SecurityManager class is abstract, none of its methods are abstract.


You still want to override a fair number of them, though, since the check methods inherited from SecurityManager always throw a SecurityException. You don't have to call on these methods yourself for the security manager to be effective.


Once the security manager is installed, various library methods call on it to check for security clearance. To install your SecurityManager, create an instance of it, and call System.setSecurityManager().


Here is a little program (SMDemo.java) that demonstrates how to use a custom security manager. You should create files named DELETEME and KEEPME before running the program:

import java.io.File;

class MySecurityManager extends SecurityManager
{
public void checkDelete( String file )
{
// Only allow the file "DELETEME" to be deleted.
if ( !file.equals( "c:\\DELETEME.txt" ) )
throw new SecurityException( "cannot delete: " + file );
}

// Override many more checkXXX() methods here...
}

public class SMDemo
{
public static void main( String argv[] )
{
MySecurityManager m = new MySecurityManager();
File deleteme = new File("c:\\DELETEME.txt" );
File keepme = new File("c:\\KEEPME.txt" );

System.setSecurityManager( m );

deleteme.delete(); // Should be OK.
keepme.delete(); // Should get a SecurityException.

System.exit(0);
}
}

After you execute the program, you should see that the file DELETEME is gone and the KEEPME file is still there, the program having triggered a SecurityException upon trying to delete it.

Classes at Runtime

Even at runtime, it is possible to access certain features of a class. This is done by way of the class Class, which implements a class descriptor object for a Java class.


You can get a class descriptor from an existing class either by using the getClass() method of java.lang.Object or by calling the static method Class.forName():

Class stringClass = Class.forName("String");


Using a class descriptor, you can find out:

  • The class name
  • The superclass
  • Whether the class is actually an interface
  • Which interfaces the class implements
  • Which ClassLoader originated this class

There is also a way to instantiate new objects from the class descriptor: the newInstance() method. This has the limitation that no arguments can be passed to the constructor, so it fails unless the class has an accessible constructor which takes no arguments.


There also doesn't seem to be any way to use the class descriptor to produce a valid operand for the right-hand side of instanceof.


Class java.lang.ClassLoader is meant to provide a way to load classes at runtime from a user-defined source. It is an abstract class.


A subclass must implement the loadClass() method to load an array of bytes from somewhere and then convert it into a class descriptor by calling resolveClass() and defineClass().

How To Make JAR File | Jar File Creation

To create .jar file that is executable and platform independent
Java Archive file.

First you need to Create manifest file that having information like
main-class (class having main method), version etc..

Ex: manifest.fs
Main-Class: HelloWorld
Version: 1.0

To create .jar file you need to use 'jar' command located at
\jdk\bin directory.

Usage:
jar {ctxu}[vfm0Mi] [jar-file] [manifest-file] [-C dir] files ...
Options:
-c create new archive
-t list table of contents for archive
-x extract named (or all) files from archive
-u update existing archive
-v generate verbose output on standard output
-f specify archive file name
-m include manifest information from specified manifest file
-0 store only; use no ZIP compression
-M do not create a manifest file for the entries
-i generate index information for the specified jar files
-C change to the specified directory and include the following file
If any file is a directory then it is processed recursively.
The manifest file name and the archive file name needs to be specified
in the same order the 'm' and 'f' flags are specified.

Example 1: to archive two class files into an archive called classes.jar:
jar cvf classes.jar Foo.class Bar.class
Example 2: use an existing manifest file 'mymanifest' and archive all the
files in the foo/ directory into 'classes.jar':
jar cvfm classes.jar mymanifest -C foo/ .

Execution Starting Point

Every java application program starts exection from :

public static void main(String[] arg) method of class.

But if class contains the static block then execution will

begin from there.


Program: StartingPoint.java
public class StartingPoint {

static {
System.out.println("static block executed");
}

public static void main(String[] arg) {
try {
System.out.println("main method executed");
} catch (Exception e) {
e.printStackTrace();
}
}
}

OUTPUT:
static block executed
main method executed

Followers