No argument constructor identifier expected - constructor

Keep getting Identifier Expected for no-argument constructor
I've tried adding String playerName; and so forth in the constructor to identify.
Also tried this.tp1.playerNamer, and taking away " = null / = 0"
but keep getting same message.
Rest of the code works fine if I take away the constructor
public class KosakowskiTennisPlayer2
{
private String playerName;
private String country;
private int rank;
private int age;
private int wins;
private int losses;
public void setPlayerName(String thePlayerName)
{ playerName = thePlayerName;}
public void setCountry(String theCountry)
{ country = theCountry;}
public void setRank(int theRank)
{ rank = theRank;}
public void setAge(int theAge)
{ age = theAge;}
public void setWins(int theWins)
{ wins = theWins;}
public void setLosses(int theLosses)
{ losses = theLosses;}
// accessor
public String getPlayerName()
{ return playerName;}
public String getCountry()
{ return country;}
public int getRank()
{ return rank;}
public int getAge()
{ return age;}
public int getWins()
{ return wins;}
public int getLosses()
{ return losses;}
KosakowskiTennisPlayer2 tp1 = new KosakowskiTennisPlayer2()
{
tp1.playerName;
tp1.country;
tp1.rank;
tp1.age;
tp1.wins;
tp1.losses;
}
Only with the constructor part is there a problem.

Related

Exception : java.util.LinkedHashMap cannot be cast to com.excel.entity.ClassA

This is the generic method through which i am accepting list of
objects and downcasting to a specific object
public Response generate(List<?> list){
List<ClassA> List1 = new ArrayList<ClassA>();
List<ClassB> List2 = new ArrayList<ClassB>();
List<ClassC> List3 = new ArrayList<ClassC>();
if(list instanceof List<?>){
List1=(List<ClassA>) list;//in this line i am getting error
addDataToExcel(List1);
}
else if(list instanceof List<?>){
List2=(List<ClassB>) list;
addDataToExcel(List1);
}
else if(list instanceof List<?>){
List3=(List<ClassC>) list;
addDataToExcel(List1);
}
This is classA
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
#Entity
#Table(name="ClassA")
public class ClassA {
#Id
#Column(name="rollNo")
private int rollNo;
#Column(name="name")
private String name;
#Column(name="english")
private double english;
#Column(name="maths")
private double maths;
#Column(name="science")
private double science;
#Column(name="totalMarks")
private double totalMarks;
#Column(name="percentage")
private double percentage;
#Column(name="status")
private boolean status;
#Lob
#Column(name="file", columnDefinition="BLOB")
private byte[] file;
public ClassA() {
// TODO Auto-generated constructor stub
}
public ClassA(int rollNo, String name, double english, double maths, double science, double totalMarks,
double percentage, boolean status, byte[] file) {
super();
this.rollNo = rollNo;
this.name = name;
this.english = english;
this.maths = maths;
this.science = science;
this.totalMarks = totalMarks;
this.percentage = percentage;
this.status = status;
this.file = file;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getEnglish() {
return english;
}
public void setEnglish(double english) {
this.english = english;
}
public double getMaths() {
return maths;
}
public void setMaths(double maths) {
this.maths = maths;
}
public double getScience() {
return science;
}
public void setScience(double science) {
this.science = science;
}
public double getTotalMarks() {
return totalMarks;
}
public void setTotalMarks(double totalMarks) {
this.totalMarks = totalMarks;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public byte[] getFile() {
return file;
}
public void setFile(byte[] file) {
this.file = file;
}
}
This is the method which accepts List and generate excel
public void add(List<ClassA> classA) {
System.out.println("entering add");
String excelFilePath = "D:/eclipse_neon/StudentInfo.xlsx";
try {
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowNum = 1;
int a=2;
for(ClassA info: classA){
System.out.println("netering loop");
Row row = sheet.getRow(rowNum++);
row.createCell(2).setCellValue(info.getEnglish());
row.createCell(3).setCellValue(info.getMaths());
row.createCell(4).setCellValue(info.getScience());
row.createCell(5).setCellFormula("SUM(C"+a+","+"D"+a+","+"E"+a+")");
row.createCell(6).setCellFormula("("+"F"+a+"*"+"100"+")"+"/"+"300");
row.createCell(7).setCellValue(info.isStatus());
a++;
}
System.out.println("after for loop");
inputStream.close();
FileOutputStream outputStream = new FileOutputStream("D:/eclipse_neon/StudentInfo.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException | EncryptedDocumentException
| InvalidFormatException ex) {
ex.printStackTrace();
}
}
I am not able to downcast to my specific List of class from generic list soo any suggestions are welcomed Thankyou
That's probably because you're sending a list as parameter containing a List and class A is not related to LinkedHashMap (not a subclass for example) and therefore it cannot cast. If you can provide more details what is class A and what is the list you're sending as arguments to your method.
Check https://www.baeldung.com/java-type-casting

GluonConnect JSON converter cannot convert object

On the client app I have this POJO
public class Chicken {
private String name;
private int age;
public Chicken(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
and I run this
RestClient get = RestClient.create().method("GET")
.host("http://localhost:8080/DevCrowd")
.path("resources/chickens");
GluonObservableList<Chicken> sample = DataProvider.retrieveList(
get.createListDataReader(Chicken.class));
System.out.println(sample);
But I get the error:
WARNING: Failed to create object of type class com.devcrowd.test.Chicken from the following json object {"id":1,"name":"AAA","age":12}
java.lang.InstantiationException: com.gluonhq.notesapp.Chicken
at java.lang.Class.newInstance(Class.java:427)
at com.gluonhq.connect.converter.JsonConverter.readFromJson(JsonConverter.java:111)
at com.gluonhq.connect.converter.JsonIterableInputConverter.next(JsonIterableInputConverter.java:108)
at com.gluonhq.connect.provider.DataProvider.lambda$retrieveList$21(DataProvider.java:194)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoSuchMethodException: com.gluonhq.notesapp.Chicken.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)
... 6 more
On the server I have this entity:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement
#Entity
#NamedQuery(name="all", query = "SELECT c FROM Chicken C")
public class Chicken {
#Id
#GeneratedValue
private long id;
private String name;
private int age;
public Chicken() {}
public Chicken(String name, int age) {
this.name = name;
this.age = age;
}
}
and this service:
#Path("chickens")
public class ChickensResource {
#Inject
ChickenService cs;
#GET
#Produces(MediaType.APPLICATION_JSON)
public String chickens() {
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
List<Chicken> chickens = cs.getAllChickens();
chickens.stream().map(chicken -> Json.createObjectBuilder()
.add("name", chicken.getName())
.add("age", chicken.getAge())
.build())
.forEach(jsonArrayBuilder::add);
return jsonArrayBuilder.build().toString();
}
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public void save(JsonObject chicken) {
String name = chicken.getString("name");
int age = chicken.getInt("age");
cs.save(new Chicken(name, age));
}
}
I can POST correctly (I check the DB and what I POST is there so this is why the error stack has a Chicken object ready) but I can't read it back. Why is that?
As you can read in the docs for JsonConverter::readFromJson:
Convert the provided JSON Object into a Java object. If a new instance could not be created from the specified targetClass in the constructor, then null will be returned.
The conversion works by inspecting all the property methods of the target class. A property method is any field that has both a getter and a setter method.
Now if you check your exception:
java.lang.InstantiationException: com.gluonhq.notesapp.Chicken
at java.lang.Class.newInstance(Class.java:427)
the reason becomes clear: the target class (com.gluonhq.notesapp.Chicken) can't be instantiated, because it looks for a parameterless constructor.
All you'll need to do is add one:
public class Chicken {
private String name;
private int age;
public Chicken() { }
public Chicken(String name, int age) {
this.name = name;
this.age = age;
}
...
}
EDIT
The DataProvider returns an observable list, and you should use the initializedProperty() to find out when the list is ready, so you can get its content:
RestClient get = RestClient.create().method("GET")
.host("http://localhost:8080/DevCrowd")
.path("/resources/chickens");
GluonObservableList<Chicken> sample = DataProvider.retrieveList(
get.createListDataReader(Chicken.class));
sample.initializedProperty().addListener((obs, ov, nv) -> {
if (nv) {
for (Chicken chicken : sample) {
System.out.println(chicken);
}
}
});

How to create another instance of your class by using the parameterized constructor

Testing your program
Create a class called Demo.java. This class will contain your main method
Create an instance of your class (an object) by using the default constructor.
Call all your objects setter (mutator) methods to assign values to your object
Call the objects display method, to print out it's values
Create another instance of your class (another object) by using the parameterized constructor
Call the objects display method, to print out it's values
public class Shoes {
//Instance Variables
private String brand;
private int cost;
private double size;
// Default Constructor
public Shoes(){
brand = "";
cost = 0;
size = 0;
}
//Constructor
public Shoes (String brand, int cost, double size)
{
this.brand = brand;
this.cost = cost;
this.size = size;
}
//Setter
public void setBrand (String brand)
{
this.brand=brand;
}
public void setCost (int cost)
{
this.cost=cost;
}
public void setSize (double size)
{
this.size=size;
}
//Getter
public String getBrand()
{
return brand;
}
public int getCost()
{
return cost;
}
public double getSize()
{
return size;
}
// Display data
public void display()
{
System.out.println(brand);
System.out.println(cost);
System.out.println(size);
}
}
public class Demo {
public static void main(String[] args) {
// Create a object
Shoes yeezys = new Shoes();
Shoes kobes = new Shoes();
yeezys.setBrand("Adidas");
yeezys.setCost(200);
yeezys.setSize(8.5);
yeezys.display();
System.out.println("");
//Second object? Need help with this
kobes.setBrand("Nike");
kobes.setCost(150);
kobes.setSize(9.5);
kobes.display();
}
}

Serialize subclass into subelement

I'm using Jackson and want to serialize subclass' fields into subelement. Unfortunately Jackson has awful documentation.
#JsonRootName(value = "subclass")
public class ProfilerTask extends Task {
private int age;
private int grade;
public ProfilerTask(String name, Date createdOn, int age, int grade) {
super(name, createdOn);
this.age = age;
this.grade = grade;
}
/**
* #return the age
*/
public int getAge() {
return age;
}
/**
* #return the grade
*/
public int getGrade() {
return grade;
}
}
I'm getting this: {"name":"test task","createdOn":1372771395040,"age":25,"grade":4}, while I actually want subclass's fields to be a subelement.
I think, you should think about composition instead of inheritance. But if you really want to have inheritance you have to change POJO class. You can create new internal class and move all properties and fields into this new class. See my example:
public class ProfilerTask extends Task {
private Subclass subclass;
public ProfilerTask(String name, long createdOn, int age, int grade) {
super(name, createdOn);
this.subclass = new Subclass();
this.subclass.age = age;
this.subclass.grade = grade;
}
public Subclass getSubclass() {
return subclass;
}
#JsonIgnore
public int getAge() {
return subclass.age;
}
#JsonIgnore
public int getGrade() {
return subclass.grade;
}
public class Subclass {
private int age;
private int grade;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
}
Now, please see my simple main method:
ObjectMapper mapper = new ObjectMapper();
ProfilerTask task = new ProfilerTask("test task", 1372771395040L, 25, 4);
System.out.println(mapper.writeValueAsString(task));
This program prints:
{"name":"test task","createdOn":1372771395040,"subclass":{"age":25,"grade":4}}
I think this is the simplest way to create sub-element in JSON with Jackson.

Hibernate n:m extractHashCode throws NullPointerException

I get the following exception while inserting an object with hibernate. Reading from the database works like a charm. I use MySQL 5.5 as database provider and hibernate 3.6.5.
I have the following database schema:
cell(id,cellid,lac,mcc,mnc,insertTime)
location(id,latitude,longitude,altitude,accuracy,heading,hdop,vdop,pdop,insertTime)
cellatlocation(servingCell,neighbourCell,location,signalStrength,insertTime)
where id in cell and location are primary keys and servingCell,neighbourCell and location is the composite primary key in cellatlocation.
java.lang.NullPointerException
at org.hibernate.type.descriptor.java.AbstractTypeDescriptor.extractHashCode(AbstractTypeDescriptor.java:88)
at org.hibernate.type.AbstractStandardBasicType.getHashCode(AbstractStandardBasicType.java:196)
at org.hibernate.type.AbstractStandardBasicType.getHashCode(AbstractStandardBasicType.java:191)
at org.hibernate.type.EntityType.getHashCode(EntityType.java:325)
at org.hibernate.type.ComponentType.getHashCode(ComponentType.java:222)
at org.hibernate.engine.EntityKey.generateHashCode(EntityKey.java:126)
at org.hibernate.engine.EntityKey.<init>(EntityKey.java:70)
at org.hibernate.engine.StatefulPersistenceContext.getDatabaseSnapshot(StatefulPersistenceContext.java:286)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:211)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:531)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:103)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:685)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:677)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:673)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:345)
at $Proxy17.saveOrUpdate(Unknown Source)
The classes I want to insert:
Cell.java
#Entity
#Table(name = "cell", catalog = "crisis")
public class Cell implements Serializable {
private static final long serialVersionUID = -8532796958180260393L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Integer mnc;
private Integer mcc;
private Long cellid;
private Integer lac;
#org.hibernate.annotations.Type(type = "org.joda.time.contrib.hibernate.PersistentDateTime")
private DateTime insertTime;
#OneToMany(mappedBy = "pk.servingCell")
private List<CellAtLocation> cellAtLocation = new LinkedList<CellAtLocation>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getMnc() {
return mnc;
}
public void setMnc(Integer mnc) {
this.mnc = mnc;
}
public Integer getMcc() {
return mcc;
}
public void setMcc(Integer mcc) {
this.mcc = mcc;
}
public Long getCellid() {
return cellid;
}
public void setCellid(Long cellid) {
this.cellid = cellid;
}
public Integer getLac() {
return lac;
}
public void setLac(Integer lac) {
this.lac = lac;
}
public DateTime getInsertTime() {
return insertTime;
}
public void setInsertTime(DateTime insertTime) {
this.insertTime = insertTime;
}
public List<CellAtLocation> getCellAtLocation() {
return cellAtLocation;
}
public void setCellAtLocation(List<CellAtLocation> cellAtLocation) {
this.cellAtLocation = cellAtLocation;
}
}
Location.java
#Entity
#Table(name = "location", catalog = "crisis")
public class Location implements Serializable {
private static final long serialVersionUID = 2197290868029835453L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Double latitude;
private Double longitude;
private Double altitude;
private Double accuracy;
private Double heading;
private Double hdop;
private Double vdop;
private Double pdop;
#org.hibernate.annotations.Type(type = "org.joda.time.contrib.hibernate.PersistentDateTime")
private DateTime insertTime;
#OneToMany(mappedBy = "pk.location")
private List<CellAtLocation> cellAtLocation = new LinkedList<CellAtLocation>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getAltitude() {
return altitude;
}
public void setAltitude(Double altitude) {
this.altitude = altitude;
}
public Double getAccuracy() {
return accuracy;
}
public void setAccuracy(Double accuracy) {
this.accuracy = accuracy;
}
public Double getHeading() {
return heading;
}
public void setHeading(Double heading) {
this.heading = heading;
}
public Double getHdop() {
return hdop;
}
public void setHdop(Double hdop) {
this.hdop = hdop;
}
public Double getVdop() {
return vdop;
}
public void setVdop(Double vdop) {
this.vdop = vdop;
}
public Double getPdop() {
return pdop;
}
public void setPdop(Double pdop) {
this.pdop = pdop;
}
public DateTime getInsertTime() {
return insertTime;
}
public void setInsertTime(DateTime insertTime) {
this.insertTime = insertTime;
}
public List<CellAtLocation> getCellAtLocation() {
return cellAtLocation;
}
public void setCellAtLocation(List<CellAtLocation> cellAtLocation) {
this.cellAtLocation = cellAtLocation;
}
}
CellAtLocation.java
#Entity
#Table(name = "cellatlocation", catalog = "crisis")
#AssociationOverrides({ #AssociationOverride(name = "pk.servingCell", joinColumns = #JoinColumn(name = "servingCell")),
#AssociationOverride(name = "pk.neighbourCell", joinColumns = #JoinColumn(name = "neighbourCell")),
#AssociationOverride(name = "pk.location", joinColumns = #JoinColumn(name = "location")) })
public class CellAtLocation implements Serializable {
private static final long serialVersionUID = -4440795783726362367L;
private CellAtLocationPk pk = new CellAtLocationPk();
private Integer signalStrength;
#EmbeddedId
private CellAtLocationPk getPk() {
return pk;
}
#SuppressWarnings("unused")
private void setPk(CellAtLocationPk pk) {
this.pk = pk;
}
#Transient
public Cell getServingCell() {
return getPk().getServingCell();
}
public void setServingCell(Cell cell) {
getPk().setServingCell(cell);
}
#Transient
public Cell getNeighbourCell() {
return getPk().getNeighbourCell();
}
public void setNeighbourCell(Cell cell) {
getPk().setNeighbourCell(cell);
}
#Transient
public Location getLocation() {
return getPk().getLocation();
}
public void setLocation(Location location) {
getPk().setLocation(location);
}
public Integer getSignalStrength() {
return signalStrength;
}
public void setSignalStrength(Integer signalStrength) {
this.signalStrength = signalStrength;
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
CellAtLocation that = (CellAtLocation) o;
if (getPk() != null ? !getPk().equals(that.getPk()) : that.getPk() != null)
return false;
return true;
}
public int hashCode() {
return (getPk() != null ? getPk().hashCode() : 0);
}
}
and finally the primary key mapping itself CellAtLocationPk.java
#Embeddable
public class CellAtLocationPk implements Serializable {
private static final long serialVersionUID = 5286485161491158083L;
private Cell servingCell;
private Cell neighbourCell;
private Location location;
#ManyToOne
public Cell getServingCell() {
return servingCell;
}
public void setServingCell(Cell servingCell) {
this.servingCell = servingCell;
}
#ManyToOne
public Cell getNeighbourCell() {
return neighbourCell;
}
public void setNeighbourCell(Cell neighbourCell) {
this.neighbourCell = neighbourCell;
}
#ManyToOne
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
CellAtLocationPk that = (CellAtLocationPk) o;
if (servingCell != null ? !servingCell.equals(that.servingCell) : that.servingCell != null)
return false;
if (neighbourCell != null ? !neighbourCell.equals(that.neighbourCell) : that.neighbourCell != null)
return false;
if (location != null ? !location.equals(that.location) : that.location != null)
return false;
return true;
}
public int hashCode() {
int result;
result = (servingCell != null ? servingCell.hashCode() : 0);
result = 31 * result + (neighbourCell != null ? neighbourCell.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
return result;
}
}
The problem is that hibernate is trying to save the relationship object, CellAtLocation instance, while the children objects, Cell and/or Location instances are not yet persisted. Thus, children objects don't have generated ids associated with them and therefore hibernate can not compute the hash for them.
Before trying to save CellAtLocation instance, try saving the children objects first by calling saveOrUpdate method on them.
For anyone also dealing with this issue, it occurred in my case simply because I did not have an open and active transaction. The stack trace did not point directly to this being the issue but can be explained as follows:
The parent item was being persisted in the cache and hibernate simply accepted the parent not having an actual ID. If we could have somehow called flush() on our connection we would have then been notified of the non-existent transaction. Instead, when the child item was to be persisted the parent's ID did not TRULY exist. When hibernate went to get the parent's hashed id for the purpose of saving the child, the NPE was thrown.
I had the same problem and figured out that the way to properly map embedded ids is by using #Embeddable, #EmbeddedId and #MapsId (which is the one missing in the problem code). The docs from #MapsId annotation states an example that fixes this issue:
Example:
// parent entity has simple primary key
#Entity
public class Employee {
#Id
private long employeeId;
private String name;
...
}
// dependent entity uses EmbeddedId for composite key
#Embeddable
public class DependentId {
private String name;
private long employeeId; // corresponds to primary key type of Employee
}
#Entity
public class Dependent {
#EmbeddedId
private DependentId dependentId;
...
#MapsId("employeeId") // maps the employeeId attribute of embedded id
#ManyToOne
private Employee employee;
}
This is the proper way to fix the issue. This way, you wouldn't need to save the entities separately (which is not a good practice). Instead, hibernate will manage the entire transaction for you by mapping the generated ids properly.
Hope this helps for anyone having this issue in the future.
Cheers,
In my case, found out that one primary key in a foreign key table has not set. Only the fields that implement hashcode int the table were set.
I too found the problem to be that hibernate is trying to save the relationship/parent object, while the child object instances are not yet persisted. I solved it by setting child object Ids to 0 and hibernate picked up from there without having to save the child objects manually.
Hope this helps.