I have a base class called "Entity" which has a static method called "construct" that returns an Entity instance. I have several different subclasses of this class (for demonstration assume we have "Fruit" and "Vegetable" as subclasses). I would like to be able to do something along the following lines:
Entity a = someFunction(Fruit, textfile)
someFunction would then pass textfile to Fruit.construct and return the Entity generated. Is there a simple way to do this?
We have a method coypObject() which accepts an object of the current class and initializes the instance variables with the variables of this object and returns it. In the main method we are instantiating the Student class and making a copy by passing it as an argument to the coypObject() method.
Arguments in Java are always passed-by-value. During method invocation, a copy of each argument, whether its a value or reference, is created in stack memory which is then passed to the method.
Static methods take all the data from parameters and compute something from those parameters, with no reference to variables. Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.
You can't. If you do need to use parameters with that class, then obviously all the methods shouldn't be static and you should create proper constructors for it. No, it's more like instance initialization blocks, and, like those, it cannot take args.
You mean something like this:
public <T> T someFunction(Class<T> clazz, String textFile) throws Throwable {
return clazz.newInstance();
}
The above code will use the no-arguments Constructor of the class (assuming there's one).
If your class needs to be instantiated with a specific constructor, you can do follow this example:
public <T> T someFunction(Class<T> clazz, String textFile) throws Throwable {
// Here I am assuming the the clazz Class has a constructor that takes a String as argument.
Constructor<T> constructor = clazz.getConstructor(new Class[]{String.class});
T obj = constructor.newInstance(textFile);
return obj;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With