Government Security
Network Security Resources

Jump to content


Java Annotation Pt 2

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

#1 Juza



  • 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.*;

public @interface Singleton {

Just for test we will create a simple class.

public class Test {

	public void 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);
			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");
		Test test2 = SingletonProxy.getInstance("test");


Let's test this!



Boom! It works!

Hope you have learned something!
Go to
Follow me

The true beginning of our end.

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