N
Nobody
Hi,
In the spirit of "most maintainable" code, I'm applying a factory method
to instantiate objects using part of a class name that's passed to the
factory method, followed by reflection and newInstance(). The code goes
something like this:
public static Product loadProductDynamically(String requestedPF)
throws UnsupportedProductFactoryException
{
Product theProduct;
try {
theProduct=
(Product) Class.forName(requestedPF + "Product").
newInstance();
} catch (InstantiationException e) {
throw new UnsupportedProductFactoryException();
} catch (IllegalAccessException e) {
throw new UnsupportedProductFactoryException();
} catch (ClassNotFoundException e) {
throw new UnsupportedProductFactoryException();
}
return theProduct;
}
This works great if everything (this class, the *Product classes) is in
the "default" package. As soon as I put the code in another named
package, the forName() method above doesn't work. Obviously you have to
specify the package part of the class.
But, how can I get the package name in a static method like the one
above without hard-coding the package name anywhere in the class?
Ideally, this kind of code should work for any class in any package,
e.g., expecting that the "*Product" classes are in the same package.
Thanks in advance!
In the spirit of "most maintainable" code, I'm applying a factory method
to instantiate objects using part of a class name that's passed to the
factory method, followed by reflection and newInstance(). The code goes
something like this:
public static Product loadProductDynamically(String requestedPF)
throws UnsupportedProductFactoryException
{
Product theProduct;
try {
theProduct=
(Product) Class.forName(requestedPF + "Product").
newInstance();
} catch (InstantiationException e) {
throw new UnsupportedProductFactoryException();
} catch (IllegalAccessException e) {
throw new UnsupportedProductFactoryException();
} catch (ClassNotFoundException e) {
throw new UnsupportedProductFactoryException();
}
return theProduct;
}
This works great if everything (this class, the *Product classes) is in
the "default" package. As soon as I put the code in another named
package, the forName() method above doesn't work. Obviously you have to
specify the package part of the class.
But, how can I get the package name in a static method like the one
above without hard-coding the package name anywhere in the class?
Ideally, this kind of code should work for any class in any package,
e.g., expecting that the "*Product" classes are in the same package.
Thanks in advance!