Government Security
Network Security Resources

Jump to content

Photo

Java Annotation Pt 2

- - - - - proxy java hash
  • Please log in to reply
No replies to this topic

#1 Juza

Juza

    Specialist

  • Sergeant Major
  • 149 posts

Posted 01 November 2010 - 02:33 PM

This is my second entry about this topic. This one is a simple example how to implement a singleton pattern without have to code it, just annotate the class.

For those who do not know what is a the singleton pattern, i will do a short explanation.
OK, a pattern is a general reusable solution to a commonly occurring problem in software design.
And the singleton pattern restricts the instances of objects to one.
All this only using annotations.

Let's make our annotation.

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
public @interface Singleton {
}


Just for test we will create a simple class.

@Singleton
public class Test {

	public void test() {
		System.out.println("test");
	}
	
}

And now the brains!


import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


public class SingletonProxy {
	
	public static Hashtable<Class<?>, Object> classes = new Hashtable<Class<?>, Object>();
	
	public static <T> T getInstance(String classname) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		Object object = null;
		Class<?> klass = Class.forName("Test");
		
		if (klass.isAnnotationPresent(Singleton.class)) {
			if (!classes.containsKey(klass)) {
				classes.put(klass, klass.newInstance());
			}
			object = findValueWithKey(klass);
		}
	
		return (T) object;
	}

	public static Object findValueWithKey(Class<?> key) {
		Object object = null;
		Set set = classes.entrySet();
		Iterator it = set.iterator();
		
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			if (entry.getKey().equals(key))
				object = entry.getValue();
		}
		return object;
	}
	
}

Our main class goes like this.

public class Main {
	
	public static void main(String[] args) throws Exception {

		Test test1 = SingletonProxy.getInstance("test");
		
		test1.test();
		System.out.println(test1.hashCode());
		
		Test test2 = SingletonProxy.getInstance("test");
		test2.test();
		System.out.println(test2.hashCode());
		
	}

}

Let's test this!

Output:

test
21171036
test
21171036


Boom! It works!

Hope you have learned something!
Go to iamjuza.blogspot.com
Follow me twitter.com/iamjuza

The true beginning of our end.






Also tagged with one or more of these keywords: proxy, java, hash