How do I call a constructor in java via reflection? [duplicate] - java

This question already has an answer here:
IllegalArgumentException with constructing class using reflection and array arguments
(1 answer)
Closed 6 years ago.
I am dumping CSV via jackson. I have a couple of mapping classes and want to pass the mapping class to the CSV export method.
I have an abstract class, extended it to each of the csv column formats. I pass the name of the class to the export function then want to map the data via the constructor for the class and dump it as CSV.
All fine until I get to creating the class that does the mapping and is to be exported.
Invocation exception/Invalid number of parameters exception.
protected String mapTransactionsToCSV(List<Object[]> results, String rowClassName)
Class rowClass = Class.forName(rowClassName);
for (Object[] component : results)
VehicleAbstract vehicle = (VehicleAbstract) rowClass.getDeclaredConstructor(Object[].class).newInstance(component);
csv.append(mapper.writer(schema).writeValueAsString(vehicle));
}
}
My specific class (and abstract class, which I just copied to try). has 2 constructors
public Bus() {}
public Bus(Object[] component) {}

See Problem with constructing class using reflection and array arguments
The problem is that newInstance already takes an array of objects. You need to wrap your object array in another array. Something like this:
component = {component}; // Wrap in a new object array
VehicleAbstract vehicle = (VehicleAbstract) rowClass.getDeclaredConstructor(Object[].class).newInstance(component);
This is the reason that you're getting an invalid number of parameters - you're passing each item in that object array as a separate parameter, instead of one parameter (the array of objects).

Related

Detecting type of object used in Java Lambda expression [duplicate]

This question already has answers here:
How Java 8 is able to infer lambdas argument type
(1 answer)
Lambda Expression without types
(3 answers)
Closed 5 months ago.
I came across a code similar to below. There is no local variable or instance variable defined as order in the class or its super class. How does Java identify variable order used below is type of Class Order and lets the developer use the methods from Order class? Howe is it also able to get an object instance with values populated?
public Data getData(
Resource resource,
Optional<Integer> myData
) {
Metadata metadata = getMetadata(
resource,
myData
);
return order ->
MyUtils
.extractJson(DataMap.class, metadata, order.getMetadata());
}
Data Interface
interface Data {
MetadataMap fetchMetadata(Order order);
}

How to create object of a class in the other and also vice versa in java? [duplicate]

This question already has answers here:
What is a StackOverflowError?
(16 answers)
Closed 4 years ago.
I have designed a GUI which has a jTextArea. I can append text to this very easily in this class. But I would also like to append text to this from methods of other classes.
For this I make the jTextArea public and create an object of that class in the other class. Now I can write to the jTextArea while executing methods in the other classes.
But it turns out that I need a method of the class I created an object in within my GUI class as well. As I do that, StackOverflowError happens. What should I do?
Instead of initializing the BTDBattlesBot object with a new keyword in AutomatedActions class, you can add a parameterized constructor which takes BTDBattlesBot object as parameters and initialize the object in this constructor. Something like below
public class AutomatedActions {
...............
private final BTDBattlesBot botWindow = null;
// Below is the parametrized constructor
public AutomatedActions(BTDBattlesBot botWindow) {
botWindow = this.botWindow;
}
..........
}
Then in the BTDBattlesBot class, while creating the object of AutomatedActions class, instead of calling the default constructor, call the newly created parametrized constructor and pass the current object of BTDBattlesBot class using this keyword. By doing this you should be able to achieve what you want
class BTDBattlesBot {
......
AutomatedActions action = new AutomatedActions(this);
......
}

Empty constructor in Java [duplicate]

This question already has answers here:
Why might one also use a blank constructor?
(10 answers)
Java entity - why do I need an empty constructor?
(8 answers)
Why Default constructor need to declare in POJO file which has Parameterized Constructor while instantiating Object?
(5 answers)
Default constructor does not initialize the instance members of the class?
(7 answers)
Closed 5 years ago.
Is it okay to use an empty constructor in Java? For example, when loading the data from a MySQL database, I want to do something like:
ResultSet set = statement.executeQuery();
while (set.next()) {
Faction faction = new Faction();
faction.setId(UUID.fromString(set.getString("id")));
faction.setName(set.getString("name"));
}
Because I already have a constructor for the faction class,
public Faction(Player player, UUID uuid) {}
I was wondering if I can have a plain constructor and just set the values as and when.
Otherwise I could create a constructor using parameters that match the mySQL data (public Faction(String name, UUID uuid, String announcement..etc), to load in.. Not sure what is best practice?
If the object state should not change when the Faction class is instantiated, provide a constructor with args and removing setter is better.
In this way, you avoid undesirable behavior.
Now, according to your saying, you probably need to set many String parameters.
Doing it with a constructor is very error prone as you may do a mistake in the parameter order when you use it.
To achieve your need, you have two main ways :
using an empty constructor and then setters as you propose (desirable if the object is mutable)
if your object is immutable, you could use the Builder pattern to construct an immutable object (You write something like : Faction faction = new Faction.Builder().name(name).uuid(uuid).announcement(announcement).build();
It depends on your use case. If you dont want the class variables to change once you set them then in that case declare those variables as final and use the parametised constructor. If you want the variables to change once you set them, then use the default constructor with setters and getters.Both the options are perfectly fine.

adding the arraylist value in a map [duplicate]

This question already has an answer here:
Regarding Map having an value of type arraylist
(1 answer)
Closed 9 years ago.
I have a query, I have a method in my class named abc of which return type is of arraylist as shown below
public List<abcinfo> getabc(String fileIdentifier)
{}
Now in the same class inside another method I need to add the outcome of the above method in the form of key as
shown below
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("GGG", getabc(String fileIdentifier));
Now I am directly calling the method name as a value please advise me is it the correct way
as all the things are in same class, Please advise
This will not compile as you are not exactly specifying a String object as an argument to the getabc method. Why are you specifying the type in his line? :
data.put("GGG", getabc(String fileIdentifier));
String identifier is not a valid argument. Pass a String argument or variable instead such as
data.put("GGG", getabc("ArgumentRelativeToTheContextOfYourMethod"));
Apart from that , there doesn't seem to be anything wrong with your code. (relative to what you asked)
The method or the method call being in the same class should not be a problem.
In your case , the HashMap will have an entry with key as GGG and value as a List returned by your getabc method.
The value however will need to be type casted to List as you have stored it as an Object
It's correct, you can call the methode inside your class (as well as outside since it is declared as public), but on reading the Object back you will have to cast it to List<abcinfo>.

Creating an object using a string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Use string in place of variable name
Is there any way in Java that allows an object to be created using a string?
Let's say, i have a class called "Toyata", is there anyway i can create an object of Toyata
using the string variable s in class Car?
public class Car{
String s = "Toyota";
}
public class Toyota{
int speed;
public Toyota(int speed){
this.speed=speed;
}
}
You can use reflection, but you need a fully qualified classname:
https://stackoverflow.com/a/4030634/1217408
EDIT:
Hovercraft Full Of Eels's comment about using a map lookup is probably far more appropriate in this situation.
You need to query for class (assuming it's in the default package this should work) via the value of s. Then you have to lookup the proper constructor via your class' getConstructor() method. Since Toyota does not contain a default constructor, you need to query for one that matches your expected parameters. In this case, it's an int. int is represented in Class form by Integer.TYPE. Finally after that is all said and done, you can call newInstance() on the constructor with the desired speed passed in and you should have a new instance ready to use. Of course there will be a few checked exceptions to handle.
Class<?> clazz = Class.forName(s);
Constructor constructor = clazz.getConstructor(new Class[] {Integer.TYPE});
Toyota toyota = (Toyota) constructor.newInstance(new Object[] {90});

Categories