Daily Archives: February 11, 2011

Breaking singleton pattern


Singleton pattern in java can be implemented by the approaches explained here

Now here is the code to break it using reflection


public class NormalClass{

 private NormalClass(){ //having private constructor
 }

 private void print(){
 System.out.println("broken");
 }

}

/////////////////////////////////

public class Main{

 public static void main(String[] args) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {

 Class c = NormalClass.class;
 final Constructor con = c.getDeclaredConstructor();
 System.out.println(con);

 final Method meth = c.getDeclaredMethod("print", null);

//---- You will get IllegalAccessException without this ---
AccessController.doPrivileged(new PrivilegedAction() {

public Object run() {
 con.setAccessible(true);// turning off the access check
 meth.setAccessible(true);// turning off the access check
return null;
 }

});

 NormalClass n = (NormalClass)con.newInstance(null);
 meth.invoke(n,null);
 }

}

Advertisements

Java Annotations


Why do we use Annotations?

Annotations give information about the java program and is not part of the program itslf
They give inforamtion to the compiler for Compiler time processing, deployment time processing and runtime processing

Some of the annotations are

@Author(
 name="vinod",
 date="3/12/2010"

)
public class MyClass{}

@suppressWarnings{value="unchecked"}
public void myMethod(){}

@override
public void run(){}

@Deprecated
public void printWriter(){}

There are two types of annotations

Simple and Meta Annotations

Simple Annotations – provided by JDK5

* Override
* Deprecated
* Suppresswarnings

Meta Annotations – Annotations of Annotation

* Target
* Retention
* Documented
* Inherited

Target – target element for which the annotation is applicable

* @Target(ElementType.TYPE) – applied to any element of a class
* @Target(ElementType.FIELD) – applied to a field or property
* @Target(ElementType.METHOD) – applied to a method level annotation
* @Target(ElementType.PARAMETER) – applied to the parameters of a method
* @Target(ElementType.CONSTRUCTOR) – applied to constructors
* @Target(ElementType.LOCAL_VARIABLE) – applied to local variables
* @Target(ElementType.ANNOTATION_TYPE) – indicates that the declared type itself is an annotation type

Retention – how long the annotations should be retained

* RetentionPolicy.SOURCE – retained only at the source level and will be ignored by the compiler
* RetentionPolicy.CLASS – retained by the compiler at compile time, but will be ignored by the VM
* RetentionPolicy.RUNTIME – retained by the VM so they can be read only at run-time

Documented – should be documented in by the javadoc tool

Inherited -annotations of the parent class is inherited to the subclass