Create an object dynamically in java [duplicate] - java

This question already has answers here:
Create new object using reflection?
(2 answers)
What is reflection and why is it useful?
(23 answers)
Closed 7 years ago.
Suppose I have this class:
public class Person {
private String name;
private int age;
//setters and getters
...
}
The following code is not correct, but I want something similar.
String className="Person";
String att1 = "name";
String att2 = "age;
object o = createClassByName(className);
setValueForAttribute(o,att1,"jack");
setValueForAttribute(o,att2,21);"

Are you familiar with hashes?
I think you could use a HashMap, which is a common Hash implementation built into the Java library:
HashMap<String,Object> person1 = new HashMap<String,Object>();
person1.put("className", "Person");
person1.put("name", "Jack");
person1.put("age", 21);
Everytime you want to change the values, do: person1.put("name", "Jill")
And to get the values, it's person1.get("name")
If you want to take the class into account, you'll have to get the className and manually compare it in your code, to do different things according to the "class" of the object (which in reality is a HashMap, but nevermind).
Small reminder: doing things this way is considered very messy ;)

Related

How to access instance variables of a class object through variable name and not through getter method [duplicate]

This question already has answers here:
Java: Getter and setter faster than direct access?
(3 answers)
Closed last year.
I have the below class with around 200 variables.
public class BaseDataDTO {
private CSVRecord rawData;
private List<InquiriesDataDTO> inquiriesData;
private ListTradesDataDTO> tradesData;
private List<CollectionsDataDTO> collectionsData;
private Long applicantId;
//cvv attributes
public String adg001;
private String adg002;
private String adg003;
private String adg004;
private String apg05;
-
-
private String apg199;
}
From a different class, I would like to access the instance variables through the variable names, is it possible to do? I need to do this since I need compare some another response with the instance variable of that class through a Map key. How can I achieve some thing to the effect of the text in bold below?
I do not want to use getter methods here since it is in a for loop for 200 times.
BaseDataDTO baseData = CSVParser.parseBaseData(fileName);
Map<String, String> attributes = fileLoader.withName("attributes.json").jsonToObject(Map.class);
for (String key : attributes.keySet()) {
String responseValue = response.getModelScores().get(0).getScoringInput().get("function_input").get(key).asText();
String expValue = baseData.get(key));
AssertEquals(responseValue, expValue);
}
Create a BaseDataDTO from your Map and check for equality via equals.
Never ever access object fields by their name string, unless you are writing low level libraries like parsers.
Accessing fields by name is done via Reflection:
String expValue = (String) BaseDataDTO.class.getDeclaredField(key).get(baseData)
Note that stuff like this is at least an order of magnitude slower than using a getter.

How to parse symbols as JSON keys in Java with Gson? [duplicate]

This question already has answers here:
How can I convert JSON to a HashMap using Gson?
(16 answers)
Converting deeply nested json to java object and vice versa
(3 answers)
Closed 4 years ago.
I want to get some ideas to handle a JSON structure like this.
Especially for the '/' key.
{
"tree":{
"/":"1234567890"
},
"parents":null
}
I created this (works if I replace / with slash in the given JSON)
private class Test {
private SubDirectory tree;
private String parents;
}
private class SubDirectory {
private String slash;
// private String /; obviously not working :D
}
using Gson with a InputStreamReader and then:
Test p = gson.fromJson(reader, Test.class);
So my first idea is to check reader and replace that / to slash.
But really ?! ...

Java 8 stream.collect(Collectors.grouppingBy()) returns map of size 0 when used on a JPA obtained list/object [duplicate]

This question already has answers here:
stream on JPA lazy list
(2 answers)
Closed 6 years ago.
I have the following class structure
public enum RPAttributeStatus {
NOT_CREATED,
UPDATED
}
public class RPAttribute{
private int id;
private RPAttributeStatus status;
}
public class RP{
private int id;
private List<RPAttribute> listOfRPAttributes;
}
//with getters and setters
After i get the RP object I want to obtain a map with the key as the RPAttributeStatus and the value should be a List<RPAttribute>
I am getting the object from a JPA Dao:
RiskProfileDao riskProfileDao = new RiskProfileDao();
RiskProfile riskProfile = riskProfileDao.findById(id);
And I'm trying to obtain the map as follows:
riskProfile.getRPAttributes().stream().collect(Collectors.groupingBy(RPAttribute::getStatus));
But I always get a map of size 0 but the RP object contains a populated list of RPAttributes that are not null, and have a status.
I cannot reproduce. I added constructors and getters and ran this piece of code:
RP riskProfile = new RP(7, Arrays.asList(new RPAttribute(1, RPAttributeStatus.UPDATED),
new RPAttribute(2, RPAttributeStatus.NOT_CREATED)));
Map<RPAttributeStatus, List<RPAttribute>> m
= riskProfile.getRPAttributes().stream().collect(Collectors.groupingBy(RPAttribute::getStatus));
System.out.println("Size " + m.size());
It prints;
Size 2
It seems to me your problem is somewhere else.

Converting an array into Array List [duplicate]

This question already has answers here:
Create ArrayList from array
(42 answers)
Closed 6 years ago.
Hi I have two Java Files as below:
case 6:
System.out.println("List All Property Details For Rent >>>");
// System.out.println(Arrays.toString(Property_list));
int i=0;
while(i<count){
ppty.property_list[i].viewPropertyDetails("RENT");
i++;
}
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
break;
}
}
}
}
Guys, This is basically an array of properties, and a Menu to do some operation with the list. I was planning to improve my code with a java ArrayList, because its more dynamic in nature. Could anyone tell me how I can convert this array (property_list) into an ArrayList? What are the changes do I need to make? Thanks in advance.
Your commented code is perfectly valid for initiliazing the arrayList.
ArrayList<Property> property_list = new ArrayList<Property>();
In java 7 or later you don't need to specify the second Property:
ArrayList<Property> property_list = new ArrayList<>();
Unlike the java Array you don't use bracket notation to access your variables you use .get(int index):
ppty.property_list.get(count)
To add a value you use .add(Object item);
ppty.property_list.add(new Property());
And you don't need to remember the size of ArrayList by storing it in a variable. The ArrayList has the .size() method which returns the number of elements in it.
Extra tips:
Here you can find extra methods the ArrayList has https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
You have setters and getters in your Property object. You could set the member variables to private and use them.
You should replace that ppty method with the constructor method like so:
public Property(int streetno,String streetname,
String suburb,
int postalcode,String contactperson,
String office,int phonenumber,
String openTime,String propertytype,
double price, String date){
this.StreetNumber = streetno;
this.StreetName=streetname;
this.Suburb=suburb;
this.PostalCode=postalcode;
this.ContactPerson=contactperson;
this.PhoneNumber=phonenumber;
this.Office=office;
this.OpenTime=openTime;
this.PropertyType=propertytype;
this.PropertyPrice=price;
this.Date = date;
}
This property_list should not be inside your Property object. This is something you should handle outside the object. For example in your public void displayMenuPanel() you could say ArrayList<Property> properties = new ArrayList<>(). If you put the list inside the object then it is tied with that object. If the object goes, the list goes.

Does string lose mutability if a new instance is created [duplicate]

This question already has answers here:
Is "new String()" immutable as well?
(15 answers)
Closed 7 years ago.
I know Strings are immutable in nature. But I have a question.
String a = new String("abc");
If we create a string like above instead of a literal, then isn't it not immutable any more since it is created as a new object? Please clarify. Thanks.
No. It doesn't. A java String is always immutable irrespective of how it is created.
Actually using new to create Strings is redundant and should be avoided in 99 percent of the cases (unless you are doing some micro-bench marking)
Immutable means an instance cannot be modified once it is created. When you look at all the methods of String, none of them actually modifies the original String passed to it. They either return the same String or create a new one.
This is a mutable object:
class Person {
private name;
Person(String name) { this.name = name; }
void setName(String name) { this.name = name; }
}
Because you can change its state after it has been created:
Person john = new Person("John");
john.setName("Fred"); //oops, John's name is not John any more...
On the other hand, once you have created a String there is no method that allows you to change the value of that string.
String john = "John";
john.setValue("Fred"); //No, that's not possible...
That does not prevent you from creating new Strings with similar or different values of course.
Your String is immutable as String is always immutable (view The Java Language Specification)
The difference between String a = "abc"; and String a = new String("abc"); is not the mutability, is the use of the String pool. When you do
String a = "abc";
you are using the Java String pool (See String intern)
And when you do
String a = new String("abc");
you are not using the String pool.
The String pool stores different String instances, that's why when you create two different objects using the pool, the references are the same.
In both cases anyways, you cannot change the state of your String instance (String is immutable).
Creating Strings using new can be avoided almost always.

Categories

Resources