Unable to instantiate sub class with parameter - java

I keep getting the error: java.lang.NoSuchMethodException: com.production.workflow.MyWorkflow.<init>(com.production.model.entity.WorkflowEntity)
I have a constructor that is expecting WorkflowEntity so I'm not able to figure out why it's saying NoSuchMethod. Is there something about constructor inheritance that is preventing this from instantiating?
My instantiation factory:
public static Workflow factory(WorkflowEntity workflowEntity) {
try {
Class<?> clazz = Class.forName(workflowEntity.getClassName()).asSubclass(Workflow.class);
Constructor c = clazz.getConstructor(WorkflowEntity.class);
Object workflowClass = c.newInstance(clazz);
return (Workflow) workflowClass;
} catch (Exception e) {
e.printStackTrace();
logger.severe("Unable to instantiate "+workflowEntity.getClassName()+" class: " + e.getLocalizedMessage());
}
return null;
}
Workflow class:
public class MyWorkflow extends Workflow {
//no constructors
Extended class:
abstract public class Workflow {
protected static final Logger logger = Logger.getLogger(Workflow.class.getName());
private WorkflowEntity entity;
protected WorkflowProcess workflowProcess;
#Autowired
private WorkflowProcessService workflowProcessService;
/* Don't use this one */
public Workflow() { }
/* Default constructor */
public Workflow (WorkflowEntity entity) {
this.entity = entity;
//get first workflow process
//#todo this should factor in rule, for multiple starting points
for (WorkflowProcessEntity workflowProcessEntity : entity.getWorkflowProcesses()) {
workflowProcess = WorkflowProcess.factory(workflowProcessEntity);
break;
}
}

There are two problems in your code:
Constructors are not automatically inherited by subclasses. You need to add the MyWorkflow(WorkflowEntity) constructor to the MyWorkflow class.
Your new instance call needs to be made with the workflowEntity instance (and not the class instance you are giving it now)
Here:
class MyWorkflow extends Workflow {
public MyWorkflow() {
super();
}
public MyWorkflow(WorkflowEntity entity) {
super(entity);
}
}
public static Workflow factory(WorkflowEntity workflowEntity) {
try {
Class<?> clazz = Class.forName(workflowEntity.getClassName())
.asSubclass(Workflow.class);
Constructor<?> c = clazz.getConstructor(WorkflowEntity.class);
Object workflowClass = c.newInstance(workflowEntity);
return (Workflow) workflowClass;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Consider the builder pattern instead of the factory pattern. Here is an example that builds a WorkFlow that takes a WorkflowEntity constructor parameter and builds a workFlow that does not take a WorkFlowEntity pattern (just showing multiple options available via a builder).
public class WorkFlowBuilder
{
private WorkflowEntity constructorParameter;
private Class workflowClass;
public WorkFlowBuilder(Class desiredWorkflowClass)
{
if (desiredWorkflowClass != null)
{
workflowClass = desiredWorkflowClass;
}
else
{
throw new IllegalArgumentException("blah blah blah");
}
}
public void setConstructorParameter(final WorkflowEntity newValue)
{
constructorParameter = newValue;
}
public WorkFlow build()
{
Object workflowObject;
if (constructorParameter != null)
{
Constructor constructor = workflowClass.getConstructor(WorkflowEntity.class);
Object workflowObject;
workflowObject = constructor.newInstance(workflowEntity);
}
else
{
workflowObject = workflowClass.newInstance();
}
return (WorkFlow)workflowObject;
}
}
Use this as follows:
WorkFlowBuilder builder = new WorkFlowBuilder(MyWorkFlow.class);
WorkflowEntity entity = new WorkFlowEntity();
WorkFlow item;
entity... set stuff.
builder.setConstructerParameter(entity)
item = builder.build();

I think you just want to pass in the workflowEntity into the constructor on the newInstance call, instead of the typed Class.

Constructors lost their outside visibility during inheritance.
You need to redefine it in MyWorkflow.
This is done so because sub classes may not support the super class creation process. So super object constructors does not make sense to sub classes and it's even unsafe if they were visible outside.
You should also remove the default constructor if your class can be used if instantiated without WorkflowEntity. Just remove it from Workflow and do not add to MyWorkflow.
UPD
You should also consider using generics to avoid class casting.
public Workflow create(WorkflowEntity workflowEntity) throws
ClassNotFoundException, NoSuchMethodException, SecurityException
, InstantiationException, IllegalAccessException
, IllegalArgumentException, InvocationTargetException {
Class<? extends Workflow> clazz = Class.forName(workflowEntity.getClassName()).asSubclass(Workflow.class);
Constructor<? extends Workflow> c = clazz.getConstructor(WorkflowEntity.class);
Workflow workflowClass = c.newInstance(clazz);
return workflowClass;
}
class WorkflowEntity {
public String getClassName() {
return "className";
};
}
class Workflow {
Workflow(WorkflowEntity entity) {
};
}
class MyWorkflow extends Workflow {
MyWorkflow(WorkflowEntity entity) {
super(entity);
}
}

Related

Factory pattern using generics

I would like to build a class that caches classes of type CachedObject using Map.
public class CachedObject {
protected Long id;
public CachedObject(Long id) {
this.id = id;
}
}
Below is the factory class.
public class CachedObjectFactory<T extends CachedObject> {
private static Logger logger = LoggerFactory.getLogger(CachedObjectFactory.class);
private Map<Long, T> cacheMap = new HashMap<>();
public T get(Class<T> type, Long id) throws CachedObjectInstantiationException {
T cachedObject = cacheMap.get(id);
try {
if(cachedObject == null) {
cachedObject = type.getDeclaredConstructor().newInstance(id);
}
} catch(Exception e) {
throw new CachedObjectInstantiationException(e.getMessage());
}
return cachedObject;
}
}
I have a class that extends CacheableObject as below:
#Component
class X extends CachedObject {
public X(Long id) {
super(id);
}
....
}
When I try to create an instance of class X that extends CachedObject using the get method in the factory as below: (please note that cachedObjectFactory is autowired using Spring)
#Component
class Y extends CachedObject {
CachedObjectFactory<CachedObject> cachedObjectFactory;
Y(Long id, CachedObjectFactory cachedObjectFactory) {
super(id);
this.cachedObjectFactory = cachedObjectFactory;
}
public void someMethod() {
X x = cachedFactory.get(X.class, id);
}
}
I get the compile time error "The method get(Class, Long) in the type CachedObjectFactory is not applicable for the arguments (Class,
Long)". How should I instantiate an object X using the factory method?
Declaring a field as CachedObjectFactory<CachedObject> doesn't really mean anything -- the parameter already has CachedObject as an upper bound.
You can get your code to compile by changing you factory to look like this:
public class CachedObjectFactory {
private Map<Long, Object> cacheMap = new HashMap<>();
public <T extends CachedObject> T get(Class<T> type, Long id) {
T cachedObject = (T)cacheMap.get(id);
try {
if(cachedObject == null) {
cachedObject = type.getDeclaredConstructor().newInstance(id);
}
} catch(Exception e) {
throw new RuntimeException(e.getMessage());
}
return cachedObject;
}
}
As you are using your factory for many classes, making it generic doesn't really make sense.
Of course if two instances of different subclasses of CachedObject have the same id you'll get a runtime ClassCastException.

How to set object that is being refereed in private inner class while creating Junit?

I have 2 java classes.
1) class1.java
public class class1
{
private class ParameterVariable
{
class2 c1;
String s;
ParameterVariable(String s)
{
this.s =s;
}
}
public void methodToTest(String s)
{
try
{
ParameterVariable pv = new ParameterVariable(s)
if(StringUtils.isNotEmpty(pv.c1.getPartNo()))
{
// Some Code
}
}
finally
{
// Some code
}
}
}
2) class2.java
public class class2
{
// pojo class
String partNo;
public String getPartNo()
{
return partNo;
}
public void setPartNo(String partNo)
{
this.partNo = partNo;
}
}
Now I want to create a Junit test case for my method. I am not able to get runtime value for class2 object.
Here is my work
private class1 = null;
protected Object createParamterVariableObject ( String s ) throws ClassNotFoundException, InstantiationException,
IllegalAccessException, InvocationTargetException,
NoSuchMethodException, SecurityException
{
Class clazz = Whitebox.getInnerClassType(class1.class, "ParameterVariable");
Constructor constructorForParameterVariable = clazz.getConstructor(String.java)
Object parameterVariableObject = constructorForParameterVariable.newInstance(String.java)
return parameterVariableObject;
}
#Test
public void junitTestCase() throws Exception
{
String s = "Sample";
Class clazz = null;
Object parameterVariableObject = null;
class2 cls2Object = new clsObject;
try
{
parameterVariableObject = createParamterVariableObject(s);
clazz = Whitebox.getInnerClassType(SupersedeImpl.class, "ParameterVariable");
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
class2 c2Object = new class2();
c2Object.setPartNo("NEW_PART_NO");
Field C1Field = (Field) parameterVariableObject.getClass().getDeclaredField("c1");
C1Field.set(parameterVariableObject, C1Field);
PowerMockito.whenNew(clazz).withArguments(s).thenReturn(parameterVariableObject);
class1 = PowerMockito.spy(class1);
class1.methodToTest(s);
// some assertion
}
I want to set some mocking value of part no that is object of class2.
Because my method is based on it.
I am getting null using these code. Can you please help me?
You can try by mocking the object class2 c1,
in your code there must be setter method that is injecting the object.
You can use that in you JUnit test case to return the mock object.
i.e. via doReturn().. when()..
After that you will get the mocked object in your code.
you can use when().. then() for other stuff.
My suggestion: make your life easier:
Change that inner class to a normal class
Create a factory that returns instances of that class
And then use dependency injection to give such a factory to your class under test. And use any ordinary mocking framework to create those objects.
Done. And not only do you avoid all those issues that complicate mocking in your version; you also end up with code that is less tightly coupled.

How to get this.getClass().getConstructor of a super class?

Is there a way for me to get a super implementation directly through getContructor? I want to call the constructor on "this class or any superclass".
The scenario details are that I have a base class that builds its data using reflection but the data is coming in from an external file. The external loader has a lookup that checks to see if data exists for a particular class and all of that is wrapped into ImplementedCard, below.
This works fine (enough) and isn't directly related to the question aside from my needing to be able to create all of these instances starting from an ImplementedCard instance:
public class Card implements DeepCopyable<Card> {
protected ImplementedCardList.ImplementedCard implementedCard;
public Card() {
this.implementedCard = ImplementedCardList.getInstance().getCardForClass(this.getClass());
this.initFromImplementedCard(this.implementedCard);
}
public Card(ImplementedCardList.ImplementedCard implementedCard) {
this.implementedCard = implementedCard;
this.initFromImplementedCard(this.implementedCard);
}
public void initFromImplementedCard(ImplementedCardList.ImplementedCard implementedCard) {
if (implementedCard != null) {
this.name_ = implementedCard.name_;
/* ... and so on */
}
}
// This deepCopy pattern is required because we use the class of each card to recreate it under certain circumstances
#Override
public Card deepCopy() {
Card copy = null;
try {
try {
copy = this.getClass().getConstructor(ImplementedCardList.ImplementedCard.class).newInstance(this.implementedCard);
} catch(NoSuchMethodException e) {
if(!this.getClass().equals(TestHero.class)) {
log.warn(this.getClass().toString() + " is missing ImplementedCard constructor");
}
copy = getClass().newInstance();
} catch(InvocationTargetException e) {
log.error("InvocationTargetException error", e);
copy = getClass().newInstance();
}
} catch(InstantiationException e) {
log.error("instantiation error", e);
} catch(IllegalAccessException e) {
log.error("illegal access error", e);
}
if (copy == null) {
throw new RuntimeException("unable to instantiate card.");
}
copy.name_ = this.name_;
/* ... and so on */
return copy;
}
}
This base class is then extended like so:
public class Minion extends Card implements CardEndTurnInterface, CardStartTurnInterface {
public Minion() {
super();
}
public Minion(ImplementedCardList.ImplementedCard implementedCard) {
super(implementedCard);
}
#Override
public void initFromImplementedCard(ImplementedCardList.ImplementedCard implementedCard) {
if (implementedCard != null) {
super.initFromImplementedCard(implementedCard);
/* custom init goes here */
}
}
/* other class details follow */
}
public abstract class Hero extends Minion implements MinionSummonedInterface {
public Hero() {
super();
}
public Hero(ImplementedCardList.ImplementedCard implementedCard) {
super(implementedCard);
}
/* no custom init; other class details follow */
}
public class Hunter extends Hero {
public Hunter() {
super();
}
public Hunter(ImplementedCardList.ImplementedCard implementedCard) {
super(implementedCard);
}
/* no custom init; other class details follow */
}
This goes on for hundreds of classes. What I want to do is pull out the constructors that do nothing but call super with the same parameters but when I do, it breaks the getConstructor call in deepCopy.
For each class, you can do:
Hero h = new Hero();
Class hc = h.getClass();
// Get super class and its constructor.
Class<?> sc = hc.getSuperclass();
Constructor scConst = sc.getConstructor(ImplementedCard.class);
// Get super class's parent and its constructor.
Class<?> ssc = sc.getSuperclass();
Constructor sscConst = ssc.getConstructor(ImplementedCard.class);
You could also put this in a loop until you get to Object.class or some other point in the class hierarchy where you'd like to break.
As #nhylated suggested, try
this.getClass().getSuperClass()
Here is a nice explanation regarding why
super.getClass()
behaves like it does.

Java - Execute a class method with a specify annotation

I have a android application, but it is not relevant.
I have a class called "Front controller" which will receive some message
through it's constructor. The message, for brievity, could be an integer.
I want somewhere else to create a new controller which will execute
a method based on the integer defined above
public class OtherController {
#MessageId("100")
public void doSomething(){
//execute this code
}
#MessageId("101")
public void doSomethingElse(){
//code
}
}
The front controller could be something like this:
public class FrontController {
private int id;
public FrontController(int id){
this.id=id;
executeProperControllerMethodBasedOnId();
}
public void executeProperControllerMethodBasedOnId(){
//code here
}
public int getId(){
return id;
}
}
So, if the Front Controller will receive the integer 100, it
will execute the method annotated with #MessageId(100). The
front controller don't know exactly the class where this method
is.
The problem which I found is that I need to register somehow
each controller class. I Spring I had #Component or #Controller
for autoloading. After each controllers are register, I need to
call the properly annotated method.
How to achieve this task? In Spring MVC, I had this system
implemented, used to match the HTTP routes. How could I implement
this in a plain java project?
Any suggestions?
Thanks to Google Reflections (hope you can integrate this in your android project.)
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections-maven</artifactId>
<version>0.9.8</version>
</dependency>
For optimisation I've added the requirement to also annotate the class with MessageType annotation and the classes should be in the same package (org.conffusion in my example):
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface MessageType {
}
The OtherController looks like:
#MessageType
public class OtherController {
#MessageId(id=101)
public void method1()
{
System.out.println("executing method1");
}
#MessageId(id=102)
public void method2()
{
System.out.println("executing method2");
}
}
The implementation will look like:
public void executeProperControllerMethodBasedOnId() {
Set<Class<?>> classes = new org.reflections.Reflections("org.conffusion")
.getTypesAnnotatedWith(MessageType.class);
System.out.println("found classes " + classes.size());
for (Class<?> c : classes) {
for (Method m : c.getMethods()) {
try {
if (m.isAnnotationPresent(MessageId.class)) {
MessageId mid = m.getAnnotation(MessageId.class);
Object o = c.newInstance();
if (mid.id() == id)
m.invoke(o);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Maybe you can optimise and build a static hashmap containing already scanned message ids.
You need to implement some of the work by yourself using reflection, I would recommend to prepare message handlers on initial phase in regards to performance. Also you possibly want to think about Singleton/Per Request controllers. Some of the ways to implement the solution:
interface MessageProcessor {
void execute() throws Exception;
}
/* Holds single instance and method to invoke */
class SingletonProcessor implements MessageProcessor {
private final Object instance;
private final Method method;
SingletonProcessor(Object instance, Method method) {
this.instance = instance;
this.method = method;
}
public void execute() throws Exception {
method.invoke(instance);
}
}
/* Create instance and invoke the method on execute */
class PerRequestProcessor implements MessageProcessor {
private final Class clazz;
private final Method method;
PerRequestProcessor(Class clazz, Method method) {
this.clazz = clazz;
this.method = method;
}
public void execute() throws Exception {
Object instance = clazz.newInstance();
method.invoke(instance);
}
}
/* Dummy controllers */
class PerRequestController {
#MessageId(1)
public void handleMessage1(){System.out.println(this + " - Message1");}
}
class SingletonController {
#MessageId(2)
public void handleMessage2(){System.out.println(this + " - Message2");}
}
class FrontController {
private static final Map<Integer, MessageProcessor> processors = new HashMap<Integer, MessageProcessor>();
static {
try {
// register your controllers
// also you can scan for annotated controllers as suggested by Conffusion
registerPerRequestController(PerRequestController.class);
registerSingletonController(SingletonController.class);
} catch (Exception e) {
throw new ExceptionInInitializerError();
}
}
private static void registerPerRequestController(Class aClass) {
for (Method m : aClass.getMethods()) {
if (m.isAnnotationPresent(MessageId.class)) {
MessageId mid = m.getAnnotation(MessageId.class);
processors.put(mid.value(), new PerRequestProcessor(aClass, m));
}
}
}
private static void registerSingletonController(Class aClass) throws Exception {
for (Method m : aClass.getMethods()) {
if (m.isAnnotationPresent(MessageId.class)) {
MessageId mid = m.getAnnotation(MessageId.class);
Object instance = aClass.newInstance();
processors.put(mid.value(), new SingletonProcessor(instance, m));
}
}
}
/* To process the message you just need to look up processor and execute */
public void processMessage(int id) throws Exception {
if (processors.containsKey(id)) {
processors.get(id).execute();
} else {
System.err.print("Processor not found for message " + id);
}
}
}

Java factory pattern - load classes dynamically

I have a lot of classes UNO,HAV,MAS,KOS
I want to create a factory pattern.
validator.load("UNO").validate();
I need dynamically load classes into validator class and return an instance.
(dynamically set name of the class and return an instance)
My problem is: how can I return the instance of a class, if I have incompatible types?
I don't know what to write in return type of method.
The main problem in the Validator CLASS.
public SegmentAbstract load(String str) {
AND
return SegmentAbsClass.forName(identify);
Main class
try{
validator.load("UNO").validate();
}catch(Exception e){
System.out.print("No class ");
}
Abstract Class (SegmentAbstract)
public abstract class SegmentAbstract {
public abstract Boolean validate();
}
Class UNO
public class UNA extends SegmentAbstract{
public Boolean validate() {
System.out.print("UNO!!");
return true;
}
}
Class Validator
public class Validator {
public SegmentAbstract load(String str) {
String identify = str.substring(0, 3);
try {
return SegmentAbsClass.forName(identify);
}
catch(Exception e) {
return this;
}
}
}
Try this :
public interface Validator {
boolean validate(Object obj);
}
public final class ValidatorFactory {
private ValidatorFactory(){}
public static Validator load(String type){
try {
Class<?> clazz = Class.forName(type);
if (Arrays.asList(clazz.getInterfaces()).contains(Validator.class)){
return (Validator) clazz.newInstance();
}
throw new IllegalArgumentException("Provided class doesn't implement Validator interface");
} catch (Exception e) {
throw new IllegalArgumentException("Wrong class provided", e);
}
}
}
Maybe this will help???
I will do something like that:
// ISegment.java
public interface ISegment {
Boolean validate();
}
// Uno.java
public class Uno implements ISegment {
public Boolean validate() {
System.out.print("UNO!!");
return true;
}
}
// SegmentFactory.java
public final class SegmentFactory {
public static enum Supported {
UNO("uno", Uno.class), /* ... */, HAV("hav", Hav.class);
private final Class<?> clazz;
private final String name;
private Supported(final String name, final Class<?> clazz) {
this.name = name;
this.clazz = clazz;
}
public Class<?> getClazz() {
return clazz;
}
public static Supported for(final String name) {
for (final Supported s : values()) {
if (s.name.equals(name) {
return s;
}
}
return null; // a default one
}
}
public static ISegment create(final Supported supp) {
if (supp == null) {
return null;
}
return supp.getClazz.newInstance();
}
private SegmentFactory() {
// avoid instantiation
}
}
usage:
final ISegment sa = SegmentFactory.create(SegmentFactory.Supported.for("uno"));
sa.validate();
Not tested!!
Take a look here. Briefly, the idea is to create a map in your factory class (Map<String,String>, key is identifier, value is fully qualified class name), and add supported classes during initialization. Then you use reflection to instantiate an object in your factory method. Also, you can avoid reflection by using Map<String, SegmentAbstract> instead of Map<String,String> and adding public abstract getNewSegment() to your SegmentAbstract class.

Categories