Right now I have 4 classes which have common method to be called depending on the case as given in below example.
Class1 class1 = new Class1();
Class1 class2 = new Class2();
Class1 class3 = new Class3();
Class1 class4 = new Class4();
MyEnum enum = MyEnum.valueOf(getString()); //getString() will return String "c1" or "c2" or ....
switch(s)
{
case c1 :
class1.add();
break;
case c2 :
class2.add();
break;
case c3 :
class3.add();
break;
case c4 :
class4.add();
break;
}
since there is a possibility of new classes later, I want to make the class initialization and method call generic. Please let me know the best way to achieve it. thanks in advance for suggestions.
I think this is a proper way to do it (without generics):
public interface ICommon {
public void add();
}
then Class1,Class2,Class3
,... should implement ICommon
interface.
With that I recommend you to create a ClassFactory like this:
public class ClassFactory {
public static ICommon getInstance() {
... //do here whatever it takes to create a concrete instance of ICommon
}
and finally, it would look like this:
ICommon someClass = ClassFactory.getInstance();
someClass.add();
}
EDIT:
Instead of using a switch statement you could add this to your ClassFactory
:
public class ClassFactory {
private static HashMap<String, String> mClassMapping = new HashMap<String, String>();
public static void registerClass(Class<?> clazz, String tag) {
String name = clazz.getName();
mClassMapping.put(tag, name);
}
public static ICommon getInstance(String tag) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
String className = mClassMapping.get(tag);
if (null == className) {
throw new ClassNotFoundException(String.format("There is no class registered for tag: %s", tag));
}
Class<?> aClass = Class.forName(className);
return (ICommon)aClass.newInstance();
}
}
Finally you could do this: At some starting point register your classes:
ClassFactory.registerClass(Class1.class, "c1");
ClassFactory.registerClass(Class2.class, "c2");
...
Then get an instance like this:
String tag = ...//get tag associated to the class somehow;
ICommon classInstance = ClassFactory.getInstance(tag); //i.e tag == "c1"
classInstance.add();
@user1849139
1) public interface genaricInterface{ public void commonMethod(); }
2)implement above interface to your class and override the method
3)public Class class1 implements genaricInterface{ public void commonMethod(){ //write your logic here for class1 } }
4)Like above class you can implement to n-number of classes in java after that
5)create instance like genaricInterface gi = new class1();
6)call method gi.commonMethod();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.