how to create a dynamic class at runtime in Java - java

Is it possible to create a new Java file from an existing Java file after changing some of its attributes at runtime?
Suppose I have a java file
public class Student {
private int rollNo;
private String name;
// getters and setters
// constructor
}
Is it possible to create something like this, provided that rollNo is a key element for the table?
public class Student {
private StudentKey key;
private String name;
//getters and setters
//constructor
}
public class StudentKey {
private int rollNo;
// getters and setters
// construcotors
}
Please help. Thanks.

Take a look at javassist.

Related

How to convert String to Set<Object>?

I have the following DTOs:
public class ConsumerDTO {
private String amount;
//...some other fields
}
public class ReceiverDTO {
private Set<PriceInfoDto> prices;
//...some other fields
}
public class PriceInfoDto {
private String amount;
//...some other fields
}
I want to convert ConsumerDTO to ReceiverDTO, p.s. map my data between differently structured objects. ConsumerDTO is my source class. ReceiverDTO is my target class. I tried this:
TypeMap<ConsumerDTO , ReceiverDTO> propertyMapper = this.mapper.createTypeMap(ConsumerDTO .class, ReceiverDTO.class);
propertyMapper.addMapping(ConsumerDTO ::getAmount, ReceiverDTO::getAmount);
But having trouble with getting amount from set in my target class. Is there a way to solve this? I also read some articles, but they show examples with simple types.
You can achieve the target object of ReceiverDTO from your source object ConsumerDTO as below:
Approach Here:
Here, I have added few more sample fields in the source as well as target class to show how to map other fields while creating a target object of type ReceiverDTO using getTargetTypeObject method.
public class Test {
public static void main(String[] args) {
//Source class objects
ConsumerDTO sourceObj = new ConsumerDTO();
sourceObj.setAmount("100");
//sample for Other fields in source object
sourceObj.setName("test");
sourceObj.setId(1000);
sourceObj.setFlag(true);
//sample for Other fields in source object
ReceiverDTO targetType = getTargetTypeObject(sourceObj);
System.out.println(targetType);
}
private static ReceiverDTO getTargetTypeObject(ConsumerDTO x) {
//Intermediate object creations
PriceInfoDto dto = new PriceInfoDto();
dto.setAmount(x.getAmount());
//Set other fields like this
dto.setName(x.getName());
dto.setId(x.getId());
dto.setFlag(x.isFlag());
//Set other fields like this
Set<PriceInfoDto> set = new HashSet<>();
set.add(dto);
//Target object
ReceiverDTO receiverDTO = new ReceiverDTO();
receiverDTO.setPrices(set);
return receiverDTO;
}
}
class ConsumerDTO {
private String amount;
private String name;
private int id;
private boolean flag;
//getters and setters
//toString
}
class ReceiverDTO {
private Set<PriceInfoDto> prices;
//getters and setters
//toString
}
class PriceInfoDto {
private String amount;
private String name;
private int id;
private boolean flag;
//getters and setters
//toString
}
Output:
ReceiverDTO{prices=[PriceInfoDto{amount='100', name='test', id=1000, flag=true}]}

Update an immutable object with Lombok in Java?

I have a domain class Person annotated with Lombok #Value thus marking it as immutable, having has 3 fields.
In my service layer, I am making a call to the repository to check if the the person exists or not.
If it does exist, I need to take the Person object from the database and update the money field.
Since it is immutable, this cannot be done. I was reading some articles and came across that this can be done using builder pattern.
I will probably need to create a updatePerson() in my Person class but not sure how to do it. Or do I need to do something else ?
Person.java:
#Value
#Builder
public class Person {
private final UUID id;
private final String job;
private final BigDecimal money;
}
I am using Java 15.
You can also use another feature of lombok, which doesn't require you to use a builder. It's called #With and using this annotation will create immutable setters, meaning that the setter returns a new object with the attributes of the old one except for the attribute that you wanted to change.
#Value
public class Person {
/* You don't need to write final if you are using #Value. Lombok will make the variables final for you.
In theory you do not even need to write private,
because Lombok makes variables private by default instead of package private.*/
private UUID id;
private String job;
#With
private BigDecimal money;
}
Person newPerson = person.withMoney(new Big decimal("10"));
In general I'm not sure if making the object immutable is really a good idea. Every variable except UUID seems like it could change in the future.
Using Lombok:
#Value
#Builder(toBuilder = true)
public class Person {
private final UUID id;
private final String job;
private final BigDecimal money;
}
personObjectFromDatabase.toBuilder().setMoney(...).build()
OR
You can use the Builder pattern in that case:
public class Person {
private final UUID id;
private final String job;
private final BigDecimal money;
public static class PersonBuilder {
private UUID id;
private String job;
private BigDecimal money;
public PersonBuilder(Person defaultPerson){
this.id = defaultPerson.getId();
this.job = defaultPerson.getJob();
this.money = defaultPerson.getMoney();
}
public PersonBuilder withId(UUID id) {
this.id = UUID;
return this;
}
public PersonBuilder withJob(String job) {
this.job = job;
return this;
}
public PersonBuilder withMoney(BigDecimal money) {
this.money = money;
return this;
}
public Person build() {
return new Person(id, job, money);
}
}
}
Use this builder like the following:
Person person = new Person.PersonBuilder(personObjectFromDatabase)
.withMoney(...)
.build();
OR
You can just create a copyWith() method:
public class Person {
...
public Person copyWith(BigDecimal money) {
return new Person(this.id, this.job, money);
}
}
The class is immutable;
you can never change the values of an instance of that class.
Instead,
you must create a new instance of the class.
Do not write a builder;
you are already using Lombok,
just use the
#Builder
annotation and Lombok will create a builder for you.
Edit: You are using the builder annotation.
The soltion you are looking for appears to be this:
you must create a new instance of the class.

Passing objects as parameters in SugarORM

I have an object extending SugarRecord that looks like this:
public class SavedDraft extends SugarRecord {
private String name;
private String difficulty;
private int sport_id;
private LocalActivity localActivity;
public SavedDraft() {
}
public SavedDraft(String name, String difficulty, int ID, LocalActivity localActivity) {
this.name = name;
this.difficulty = difficulty;
this.sport_id = ID;
this.localActivity = localActivity;
}
}
The problem is that I always get a null object when I try to get the localActivity object from the database (see: SavedDraft.findById(SavedDraft.class, 1).getLocalActivity()), and I'm just wondering if it's possible to save objects as parameters in SugarORM at all.
This would be a relationship and you would need the LocalActivity to extend SugarRecord also.
See the documentation of Book and Author: http://satyan.github.io/sugar/creation.html

How to refer to an inner class inside a list in Java

after messing around with parsing a JSON response with GSON for a day, I finally figured out how to get my javabeans right in order to extract my data from the response. This is the layout of my nested classes and lists:
public class LocationContainer {
public class paging {
private String previous;
private String next;
}
private List<Datas> data;
public class Datas {
private String message;
private String id;
private String created_time;
public class Tags {
private List<Data> datas;
public class Data {
private String id;
private String name;
}
}
public class Application {
private String id;
private String name;
}
public class From {
private String id;
private String name;
}
public class Place {
private String id;
private String name;
public class Location {
private int longitude;
private int latitude;
}
}
}
}
Now I am trying to get a hold of the name string inside the place class and the created_time string, but since I am quite a noob, I can't seem to figure it out.
I was able to extract the created_time string by using
String time = gson.toJson(item.data.get(1).created_time);
However using
String name = gson.toJson(item.data.get(1).Place.name);
doesnt work.
The item class is an instance of LocationContainer filled with the output from GSON.
Any pointers would be greatly appreciated.
created_time is a member variable of Data, so your first line is fine.
However, Place is not a member variable, it's just a class definition. You probably need to instantiate a member variable inside your Data class, e.g.:
private Place place;

Where to get Java eclipse extention\shourtcut for getters setters generation?

So I started to write a POJO class, created public variables and now want to get getters and setters for them (folowing Java Naming Conventions)
so I have for example something like
package logic;
import java.util.Set;
import java.util.HashSet;
public class Route {
private Long id;
private String name;
private int number;
private Set busses = new HashSet();
}
which eclipse extention and in it which shourtcut will create Getters and setters for me to get something like
package logic;
import java.util.Set;
import java.util.HashSet;
public class Route {
private Long id;
private String name;
private int number;
private Set busses = new HashSet();
public Route(){
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setNumber(int number) {
this.number = number;
}
public void setBusses(Set busses) {
this.busses = busses;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
public Set getBusses() {
return busses;
}
}
I think this is availble by default using Ctrl + Shift + G ( I may have set this shortcut myself)
Or go to the Source menu, and select the Generate Getters and Setters option.
You can modify the keyboard short cut (and many others) by going to
Window->Preferences
Expand the "General" option
Select the "Keys" option
In Eclipse, right click on the source code and choose Source -> Generate Getters and Setters.
This will open a dialog box where you can choose which of the class members you want to generate for. You can also specify either getters or setters only as well as generating Javadoc comments.
I use this all the time, very handy function!

Categories

Resources