Factory example and Generic Class

Example1

Class<Foo> klass = Foo.class;
Foo f = klass.newInstance();
Foo f = klass.cast(Object);

ref : http://stackoverflow.com/questions/1094023/why-is-javas-classt-generic

class Factory{

    public static MotherClass getMotherClass(){
        Class<? extends MotherClass> whateverClass = ChildClass.class
        MotherClass motherObject;
        motherObject = whateverClass.newInstance();
        return motherObject;
    }
}

Factory.getMotherClass().motherMethod(variable);
class Foo<T> {
    final Class<T> typeParameterClass;

    public Foo(Class<T> typeParameterClass) {
        this.typeParameterClass = typeParameterClass;
    }

    public void bar() {
        // you can access the typeParameterClass here and do whatever you like
    }
}

ref : http://stackoverflow.com/questions/3437897/how-to-get-a-class-instance-of-generics-type-t

Example2

public class OrderedPair<K, V> implements Pair<K, V> {

    private K key;
    private V value;

    public OrderedPair(K key, V value) {
	this.key = key;
	this.value = value;
    }

    public K getKey()	{ return key; }
    public V getValue() { return value; }
}

Pair<String, Integer> p1 = new OrderedPair<String, Integer>("Even", 8);

ref : https://docs.oracle.com/javase/tutorial/java/generics/types.html

Class Factory{
     public static final <T> MyInstance<T> genInstance(Class<T> class)
     {
         return new MyInstance<T>(class);
     }
}
...
Class WhatEver{
   public static final MyInstance<String> CONSTANCE1 = Factory.genInstance(String.class);
}
...
WhatEver2.CONSTANCE1.InstanceMethod(param);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s