Output showing null values. how to resolve - java

i have three classes :
CustomerData.java
import java.util.Date;
public class CustomerData
{
private String FirstName;
private String LastName;
private int TaxId;
private String HomePhone;
private String WorkPhone;
private String HomeAddress;
private Date Dob;
private String EmployerName;
private boolean isEmployed;
private String ProDescription;
private String IsSameAsPrevious;
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public int getTaxId() {
return TaxId;
}
public void setTaxId(int taxId) {
TaxId = taxId;
}
public String getHomePhone() {
return HomePhone;
}
public void setHomePhone(String homePhone) {
HomePhone = homePhone;
}
public String getWorkPhone() {
return WorkPhone;
}
public void setWorkPhone(String workPhone) {
WorkPhone = workPhone;
}
public String getHomeAddress() {
return HomeAddress;
}
public void setHomeAddress(String homeAddress) {
HomeAddress = homeAddress;
}
public Date getDob() {
return Dob;
}
public void setDob(Date dob) {
Dob = dob;
}
public String getEmployerName() {
return EmployerName;
}
public void setEmployerName(String employerName) {
EmployerName = employerName;
}
public boolean isEmployed() {
return isEmployed;
}
public void setEmployed(boolean isEmployed) {
this.isEmployed = isEmployed;
}
public String getProDescription() {
return ProDescription;
}
public void setProDescription(String proDescription) {
ProDescription = proDescription;
}
public String getIsSameAsPrevious() {
return IsSameAsPrevious;
}
public void setIsSameAsPrevious(String isSameAsPrevious) {
IsSameAsPrevious = isSameAsPrevious;
}
}
MainCntrlr.java
public class MainCntrlr {
public static void main(String[] args)
{
CustomerData customerData=new CustomerData();
customerData.setFirstName("RAVI");
customerData.setLastName("Shekhar");
customerData.setHomePhone("123456789");
customerData.setWorkPhone("1256554634");
customerData.setHomeAddress("Banagalore");
customerData.setEmployerName("ABc");
customerData.setProDescription("New Produtc");
customerData.setTaxId(1233434343);
ContrOne ctr=new ContrOne();
ctr.displayInformation();
}
}
ContrOne.java
import com.blr.CustomerData;
public class ContrOne
{
public void displayInformation()
{
CustomerData cd=new CustomerData();
System.out.println("displaying customer Info");
System.out.println(cd.getFirstName());
System.out.println(cd.getLastName());
System.out.println(cd.getHomePhone());
System.out.println(cd.getWorkPhone());
System.out.println(cd.getEmployerName());
System.out.println(cd.getProDescription());
System.out.println(cd.getDob());
System.out.println(cd.getTaxId());
}
}
Output is :
displaying customer Info
null
null
null
null
null
null
null
0

In your method ContrOne.displayInformation() you create a new new CustomerData() object. Thus it is not properly initialized. Maybe you want to pass customerData from your main method to displayInformation?

You are creating a CustomerData object in MainCntrlr class but not passing it to the ContrOne class. ContrOne is creating it's own CustomerData object and printing it's values which are null.
A possible solution could be to change the signature of displayInfo and pass the CustomerData object to this method from MainCntrlr class.
A few other points to note
The class names are confusing. It is not clear why you have created MainCntrlr and ContrOne classes separately.
If all you want is to display Customer information, you may want to override the toString() method in CustomerData class instead.

Your ContrOne.displayInformation() instantiates a new CustomerData() object to cd but never populates fields in it.
If you want your ContrOne to display information, rather do this:
public class ContrOne {
public void displayInformation(CustomerData cd) {
System.out.println("displaying customer Info");
System.out.println(cd.getFirstName());
System.out.println(cd.getLastName());
System.out.println(cd.getHomePhone());
System.out.println(cd.getWorkPhone());
System.out.println(cd.getEmployerName());
System.out.println(cd.getProDescription());
System.out.println(cd.getDob());
System.out.println(cd.getTaxId());
}
}
and in MainCntrlr
public static void main(String[] args) {
CustomerData customerData=new CustomerData();
customerData.setFirstName("RAVI");
customerData.setLastName("Shekhar");
customerData.setHomePhone("123456789");
customerData.setWorkPhone("1256554634");
customerData.setHomeAddress("Banagalore");
customerData.setEmployerName("ABc");
customerData.setProDescription("New Produtc");
customerData.setTaxId(1233434343);
ContrOne ctr=new ContrOne();
ctr.displayInformation(customerData);
}

Related

How do I leverage a json mapping file to convert from one pojo to another pojo?

I have two POJOs (Person.java and User.java) that contain similar information. See below:
public class Person {
private String first_name;
private String last_name;
private Integer age;
private Integer weight;
private Integer height;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
}
public class User {
private String name_first;
private String name_last;
private Integer my_age;
private Integer my_weight;
private String social_security;
public String getName_first() {
return name_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public String getName_last() {
return name_last;
}
public void setName_last(String name_last) {
this.name_last = name_last;
}
public Integer getMy_age() {
return my_age;
}
public void setMy_age(Integer my_age) {
this.my_age = my_age;
}
public Integer getMy_weight() {
return my_weight;
}
public void setMy_weight(Integer my_weight) {
this.my_weight = my_weight;
}
public String getSocial_security() {
return social_security;
}
public void setSocial_security(String social_security) {
this.social_security = social_security;
}
}
I have defined a mapping.json file as shown below using GSON.
{
"columnMap": [
{
"userColumn": "name_first",
"personColumn": "first_name"
},
{
"userColumn": "last_first",
"personColumn": "first_last"
},
{
"userColumn": "my_age",
"personColumn": "age"
},
{
"userColumn": "my_weight",
"personColumn": "weight"
}
]
}
public class Mapping {
private ArrayList<Pair> columnMap;
public Mapping(){
columnMap = new ArrayList<>();
}
public ArrayList<Pair> getColumnMap() {
return columnMap;
}
public void setColumnMap(ArrayList<Pair> columnMap) {
this.columnMap = columnMap;
}
}
I am writing a utility class helper function that converts between a Person and User object the mapped pairs.
public class Pair {
private String userColumn;
private String personColumn;
public String getUserColumn() {
return userColumn;
}
public void setUserColumn(String userColumn) {
this.userColumn = userColumn;
}
public String getPersonColumn() {
return personColumn;
}
public void setPersonColumn(String personColumn) {
this.personColumn = personColumn;
}
public static void main(String args[]){
}
}
My question is below:
As you can see the returnVal object is being set by me (the programmer) to convert from a User POJO to a Person POJO. How do I leverage the pre-defined mapping.json to do this? The reason I am asking is in the future, the mapping.json file may change (maybe the weight mapping no longer exists). So I am trying to avoid re-programming this Utility.userToPerson() function. How can I achieve this? I am thinking Java reflection is the way to go, but I would like to hear back from the Java community.
public class Utility {
public static Person userToPerson(User u){
Person returnVal = new Person();
returnVal.setAge(u.getMy_age()); // <-- Question How do I leverage mapping.json here?
returnVal.setFirst_name(u.getName_first());
returnVal.setLast_name(u.getName_last());
returnVal.setWeight(u.getMy_weight());
return returnVal;
}
}
You can introspect the beans (i.e. User and Person) for the field names and call corresponding getter from User to fetch the value. Later call corresponding setter in Person.
Here I have taken userToPersonFieldsMap for mapping the field, you can load mapping from JSON file and construct the map accordingly.
Important code section is the for loop, where it dynamically calls getter and setter and does the job.
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class UserToPersonMapper {
public static void main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
Map<String, String> userToPersonFieldsMap = new HashMap<>();
userToPersonFieldsMap.put("name_first", "first_name");
userToPersonFieldsMap.put("last_first", "first_last");
userToPersonFieldsMap.put("age", "personAge");
//existing user
User user = new User("Tony", "Stark", 20);
//new person - to be initialised with values from user
Person person = new Person();
for (Map.Entry<String, String> entry : userToPersonFieldsMap.entrySet()) {
Object userVal = new PropertyDescriptor(entry.getKey(), User.class).getReadMethod().invoke(user);
new PropertyDescriptor(entry.getValue(), Person.class).getWriteMethod().invoke(person, userVal);
}
System.out.println(user);
System.out.println(person);
}
}
class User {
private String name_first;
private String last_first;
private int age;
public User(String name_first, String last_first, int age) {
this.name_first = name_first;
this.last_first = last_first;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName_first() {
return name_first;
}
public String getLast_first() {
return last_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public void setLast_first(String last_first) {
this.last_first = last_first;
}
#Override
public String toString() {
return "User{" +
"name_first='" + name_first + '\'' +
", last_first='" + last_first + '\'' +
", age=" + age +
'}';
}
}
class Person {
private String first_name;
private String first_last;
private int personAge;
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public void setFirst_last(String first_last) {
this.first_last = first_last;
}
public String getFirst_name() {
return first_name;
}
public String getFirst_last() {
return first_last;
}
public int getPersonAge() {
return personAge;
}
public void setPersonAge(int personAge) {
this.personAge = personAge;
}
#Override
public String toString() {
return "Person{" +
"first_name='" + first_name + '\'' +
", first_last='" + first_last + '\'' +
", personAge=" + personAge +
'}';
}
}
You can tweak and try it out this example to make it more align with your requirement.
Note:
This solution uses reflection.

Example of ClassName.method1Name().method2Name();

Hi any one give me example of ClassName.method1Name().method2Name() what is this please give me simple java program example of this.I am confusing of this code.
ClassName.get1().get2().get3() is just a chain of method calls on successive classes. Imagine 3 objects:
class ClassName {
public static o1 get1() {
return new o1();
}
}
class o1 {
public o2 get2() {
return new o2();
}
}
class o2 {
public o3 method3() {
return new o3();
}
}
In each instance, the function call returned another object, which itself had a method to call, and so on and so forth.
Return current object reference from method call using return this;
public class ReturnClassType {
private String firstname;
private String lastname;
public ReturnClassType firstName(String firstname){
this.firstname = firstname;
return this;
}
public ReturnClassType lastName(String lastname){
this.lastname = lastname;
return this;
}
public String getName(){
return firstname + " " + lastname;
}
public static void main(String[] args) {
String Name = new ReturnClassType().firstName("Vicky").lastName("Thakor").getName();
System.out.println(Name);
}
}
Class Employee{
public Static List<Employee> list=new ArrayList<Employee>();
private String name;
Employee(){
public Employee(){
name = "";
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
}
public static void main(String [] args){
Employee e = new Employee();
e.setname("test");
Employee e2 = new Employee();
e2.setname("test2");
Employee.list.add(e);
Employee.list.add(e2);
for(int i = 0 ; i < Employee.list.size(); i++){
System.out.println(Employee.list.get(i).getName());
}
}

Mybatis There is no getter for property

I'm working with Mybatis to batch insert data,specifically my parameterType is a class,which has a List property,so I use foreach to do the traversal.But it didn't work,here are the debug and codes.Thanks.
DEBUG
here is the sql:
<insert id="batchInsertSn" parameterType="domain.collectSn.IbSnTransit">
insert into
ib_sn_transit (
sn, inbound_no, container_no,
goods_no,goods_name, owner_no,
owner_name,create_user,update_user,
create_time,update_time,yn,
org_no,org_name,distribute_no,
warehouse_no,receiving_no,supplier_no
,out_wave_no)
values
<foreach collection="snList" item="item" index="index" separator="," >
(
#{item.sn,jdbcType=VARCHAR}, #{inboundNo,jdbcType=VARCHAR}, #{containerNo,jdbcType=VARCHAR},
#{goodsNo,jdbcType=VARCHAR},#{goodsName,jdbcType=VARCHAR},#{ownerNo,jdbcType=VARCHAR},
#{ownerName,jdbcType=VARCHAR}, #{createUser,jdbcType=VARCHAR}, #{updateUser,jdbcType=VARCHAR},
now(),now(),#{yn,jdbcType=TINYINT},
#{orgNo,jdbcType=VARCHAR},#{orgName,jdbcType=VARCHAR},#{distributeNo,jdbcType=VARCHAR},
#{warehouseNo,jdbcType=VARCHAR},#{receivingNo,jdbcType=VARCHAR},#{supplierNo,jdbcType=VARCHAR}
,#{outWaveNo,jdbcType=VARCHAR}
)
</foreach>
</insert>
here is the class
public class IbSnTransit {
private String outWaveNo;
private String queryUser;
private String finishFlag;
private Integer id;
private String inboundNo;
private String sn;
private String snStart;
private String snEnd;
private String containerNo;
private String goodsNo;
private String goodsName;
private String ownerNo;
private String ownerName;
private String createUser;
private Date createTime;
private String updateUser;
private Date updateTime;
private Integer yn;
private String orgNo;
private String orgName;
private String distributeNo;
private String warehouseNo;
private String receivingNo;
private String supplierNo;
private List<String> snList;
public String getSupplierNo() {
return supplierNo;
}
public void setSupplierNo(String supplierNo) {
this.supplierNo = supplierNo;
}
public Integer getId() {
return id;
}
public void setId(Integer id){
this.id = id;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public String getOrgName() {
return orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public String getSn() {
return sn;
}
public void setSn(String sn){
this.sn = sn;
}
public String getInboundNo() {
return inboundNo;
}
public void setInboundNo(String inboundNo) {
this.inboundNo = inboundNo;
}
public String getGoodsNo() {
return goodsNo;
}
public void setGoodsNo(String goodsNo) {
this.goodsNo = goodsNo;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public String getContainerNo() {
return containerNo;
}
public void setContainerNo(String containerNo) {
this.containerNo = containerNo;
}
public String getOwnerNo() {
return ownerNo;
}
public void setOwnerNo(String ownerNo) {
this.ownerNo = ownerNo;
}
public String getCreateUser() {
return createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdateUser() {
return updateUser;
}
public void setUpdateUser(String updateUser) {
this.updateUser = updateUser;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getYn() {
return yn;
}
public void setYn(Integer yn) {
this.yn = yn;
}
public String getDistributeNo() {
return distributeNo;
}
public void setDistributeNo(String distributeNo) {
this.distributeNo = distributeNo;
}
public String getOrgNo() {
return orgNo;
}
public void setOrgNo(String orgNo) {
this.orgNo = orgNo;
}
public String getWarehouseNo() {
return warehouseNo;
}
public void setWarehouseNo(String warehouseNo) {
this.warehouseNo = warehouseNo;
}
public String getSnStart() {
return snStart;
}
public void setSnStart(String snStart) {
this.snStart = snStart;
}
public String getSnEnd() {
return snEnd;
}
public void setSnEnd(String snEnd) {
this.snEnd = snEnd;
}
public String getReceivingNo() {
return receivingNo;
}
public void setReceivingNo(String receivingNo) {
this.receivingNo = receivingNo;
}
public String getFinishFlag() {
return finishFlag;
}
public void setFinishFlag(String finishFlag) {
this.finishFlag = finishFlag;
}
public String getQueryUser() {
return queryUser;
}
public void setQueryUser(String queryUser) {
this.queryUser = queryUser;
}
public String getOutWaveNo() {
return outWaveNo;
}
public void setOutWaveNo(String outWaveNo) {
this.outWaveNo = outWaveNo;
}
public List<String> getSnList() {
return snList;
}
public void setSnList(List<String> snList) {
this.snList = snList;
}
}
the result
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named '' in 'class java.lang.String'
IbSnTransit.snList is declared as List of String.class objects so, when you use #{item.sn,jdbcType=VARCHAR} in your mapper you are asked for a property sn in the String.class. Maybe you must use #{item,jdbcType=VARCHAR} instead.

How to add value from another class (java)

I have two classes: profesor and subject
public class Profesor {
private int numbClassroom;
public Profesor(int numbClassroom) {
this.numbClassroom = numbClassroom;
}
public int getNumbClassroom() {
return numbClassroom;
}
public void setNumbClassroom(int numbClassroom) {
this.numbClassroom = numbClassroom;
}
public String ToString(){
return "Number of classroom: "+numbClassroom;
} }
The second class is:
public class Subject{
String name;
Profesor lecturer = new Profesor();
Date yearOfStudy;
public void Dodeli(Profesor p){
??????
}}
I do not know how to add professor like a lecturer to a current subject
Like this? I don't see any problem.
public void Dodeli(Profesor p){
lecturer = p;
}
Profesor lecturer = new Profesor();
No need to instantiate lecturer. Just declare it. Then have getter/setter methods for it
Then you can assign Professor to Subject
Subject subj = new Subject("OOP"); //assuming you have corresponding constructor
subj.setLecturer(new Professor()); //or if you have existing prof object
Maybe require something like this : try to encapsulate your code
public class Professor {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Subject{
private String name;
private Professor professor;
private int numbClassroom;
private Date yearOfStudy;
public int getNumbClassroom() {
return numbClassroom;
}
public void setNumbClassroom(int numbClassroom) {
this.numbClassroom = numbClassroom;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Professor getProfesor() {
return professor;
}
public void setProfesor(Professor profesor) {
this.professor = profesor;
}
public void Dodeli(){
System.out.println("Pofessor "+getProfesor().getName()+" is teaching "+getName()+" in Room NO :"+getNumbClassroom());
}
}
public class TestImpl {
public static void main(String arr[])
{
Subject subject = new Subject();
Professor professor = new Professor();
subject.setName("Biology");
professor.setName("MR.X");
subject.setNumbClassroom(1111);
subject.setProfesor(professor);
subject.Dodeli();
}
}

XMLEncoder - Runtime Exception

I have been playing around with serialization-XML in java and am a little stuck. When I run this program I get two exceptions and I am not sure what the cause is:
java.lang.InstantiationException: Ship
Continuing ...
java.lang.Exception: XMLEncoder: discarding statement XMLEncoder.writeObject(Ship);
Continuing ...
I suspect that there is something wrong with the class that I am trying to serialize because when I use an example of the internet it works fine.
Can someone please point out what mistake I am making.
Main:
public class Main {
private static final String XMLLocation = "xmlTest.xml";
static ObjectSerializationToXML serializer = new ObjectSerializationToXML();
public Main() {
// TODO Auto-generated constructor stub
}
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Ship ship = new Ship("name", "324");
serializer.serializeObjectToXML(XMLLocation, ship);
}
}
Object Serialization-XML Class:
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class ObjectSerializationToXML {
/**
* <span id="IL_AD10" class="IL_AD">This method</span> saves (serializes) any java bean object into xml file
*/
public void serializeObjectToXML(String xmlFileLocation,
Object objectToSerialize) throws Exception {
FileOutputStream os = new FileOutputStream(xmlFileLocation);
XMLEncoder encoder = new XMLEncoder(os);
encoder.writeObject(objectToSerialize);
encoder.close();
}
/**
* Reads Java Bean Object From XML File
*/
public Object deserializeXMLToObject(String xmlFileLocation)
throws Exception {
FileInputStream os = new FileInputStream(xmlFileLocation);
XMLDecoder decoder = new XMLDecoder(os);
Object deSerializedObject = decoder.readObject();
decoder.close();
return deSerializedObject;
}
}
Object To Serialize (My object that causes the exception):
public class Ship {
private String name;
private String yearBuilt;
public Ship(String name, String yearBuilt) {
this.name = name;
this.yearBuilt = yearBuilt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getYearBuild() {
return yearBuilt;
}
public void setYearBuild(String yearBuild) {
this.yearBuilt = yearBuild;
}
#Override
public String toString() {
return "ship [name=" + name + ", yearBuilt=" + yearBuilt + "]";
}
}
Object To Serialize (example from the internet that works):
public class MyBeanToSerialize {
private String firstName;
private String lastName;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Whenever any class containing parameterized constructor and trying to serialize, then it should be only instantiated by default Constructor. So, XMLEncoder requires an object to serialize it by default constructor.
Ship class must implement the default constructor while it is containing parameterized constructor because whenever Ship class becomes to serializable, it would be looking for default constructor to instantiate for XMLEncoder.
Please find corrected Ship class as per below.
public class Ship {
private String name;
private String yearBuilt;
public Ship(String name, String yearBuilt) {
this.name = name;
this.yearBuilt = yearBuilt;
}
//Default constructor must be implemented for XMLEncoder serializing
public Ship() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getYearBuild() {
return yearBuilt;
}
public void setYearBuild(String yearBuild) {
this.yearBuilt = yearBuild;
}
#Override
public String toString() {
return "ship [name=" + name + ", yearBuilt=" + yearBuilt + "]";
}
}

Categories