Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a static class as an argument in Java

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?

like image 371
user491880 Avatar asked Aug 21 '12 21:08

user491880


People also ask

Can we pass class as an argument in Java?

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.

How do you pass an argument to a class in Java?

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.

Can we pass parameters to static method in Java?

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.

How do you pass a parameter to a static block in Java?

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.


1 Answers

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;
}
like image 65
Shivan Dragon Avatar answered Sep 21 '22 07:09

Shivan Dragon