来源:QQ中的qun
[code]package com.common.dao;
interface DBDao
{
public int delete();
}
class Table1 implements DBDao
{
public int delete()
{
System.out.println("Table1.delete");
return 0;
}
}
class Table2 implements DBDao
{
public int delete()
{
System.out.println("Table2.delete");
return 0;
}
}
public class Factory
{
public static void main(String args[])
{
Factory.getInstance("com.common.dao.Table1").delete();
Factory.getInstance("com.common.dao.Table2").delete();
}
public static <U extends DBDao>U getInstance(String clsName)
{
try
{
Class cls = Class.forName(clsName);
return (U) cls.newInstance();
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}
[/code]
与下面的不用范型效果一样
[code]
package com.common.dao;
interface DBDao
{
public int delete();
}
class Table1 implements DBDao
{
public int delete()
{
System.out.println("Table1.delete");
return 0;
}
}
class Table2 implements DBDao
{
public int delete()
{
System.out.println("Table2.delete");
return 0;
}
}
public class Factory
{
public static void main(String args[])
{
((DBDao)Factory.getInstance("com.common.dao.Table1")).delete();
((DBDao)Factory.getInstance("com.common.dao.Table2")).delete();
}
public static Object getInstance(String clsName)
{
try
{
Class cls = Class.forName(clsName);
return cls.newInstance();
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}
[/code]
[code]package com.common.dao;
interface DBDao
{
public int delete();
}
class Table1 implements DBDao
{
public int delete()
{
System.out.println("Table1.delete");
return 0;
}
}
class Table2 implements DBDao
{
public int delete()
{
System.out.println("Table2.delete");
return 0;
}
}
public class Factory
{
public static void main(String args[])
{
Factory.getInstance("com.common.dao.Table1").delete();
Factory.getInstance("com.common.dao.Table2").delete();
}
public static <U extends DBDao>U getInstance(String clsName)
{
try
{
Class cls = Class.forName(clsName);
return (U) cls.newInstance();
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}
[/code]
与下面的不用范型效果一样
[code]
package com.common.dao;
interface DBDao
{
public int delete();
}
class Table1 implements DBDao
{
public int delete()
{
System.out.println("Table1.delete");
return 0;
}
}
class Table2 implements DBDao
{
public int delete()
{
System.out.println("Table2.delete");
return 0;
}
}
public class Factory
{
public static void main(String args[])
{
((DBDao)Factory.getInstance("com.common.dao.Table1")).delete();
((DBDao)Factory.getInstance("com.common.dao.Table2")).delete();
}
public static Object getInstance(String clsName)
{
try
{
Class cls = Class.forName(clsName);
return cls.newInstance();
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}
[/code]