Create instance of a class and set variables - java

in C# you can create a instance of a class and set the values of variables at the same time:
public class Object
{
public virtual long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Version { get; set; }
public long ParentId { get; set; }
}
public class Start
{
Object object= new Object()
{
Id = 1,
Name = name,
ParentId = parentId,
Description = null,
Version= 2
};
}
Is this possible in Java aswell and how?

The standard way for setting values when creating an instance is to just have a constructor:
class ExampleObject {
long id;
String name;
String description;
int version;
long parentId;
public ExampleObject(final long id, final String name, final String description, final int version, final long parentId) {
this.id = id;
this.name = name;
this.description = description;
this.version = version;
this.parentId = parentId;
}
}
And then call it like:
ExampleObject exampleObject = new ExampleObject(1, name, null, 2, parentId);
It is possible to use a similar syntax to what you have shown, but it has quite a few downsides which you should research about before using it (and you also cannot use variables with this):
ExampleObject exampleObject = new ExampleObject() {{
id = 1;
name = "";
parentId = 2;
description = null;
version = 2;
}};
class ExampleObject {
long id;
String name;
String description;
int version;
long parentId;
}
What this does is creates an anonymous class with a static initialiser block. A static initialiser block looks like:
class ExampleObject {
long id;
String name;
String description;
int version;
long parentId;
{
id = 1;
name = "";
parentId = 2;
description = null;
version = 2;
}
}

You can create a constructor that accepts values for all the fields. This way, you can create a new instance of that object and set the values you want at the same time:
public class MyClass {
public long id;
public String name;
public String description;
public int version;
public long parentId;
/** Constructor **/
public MyClass(long id, String name, String description, int version, long parentId) {
this.id = id;
this.name = name;
this.description = description;
this.version = version;
this.parentId = parentId;
}
}
public static void main(String args[]) {
MyClass myClass = new MyClass(1, "name", "description", 1, 1);
}
By the way, it's not recommended (although you can) to name a class Object in Java, since Java also has a class with that very same name, and all Java classes extend from it (can lead to confussion).

public class Object
{
public long id;
public String name;
public String description;
public int version;
public long parentId;
public Object(long Id,string Name,string Description,int Version,long Parent_Id)
{
this.Id =Id ;
this.Name =Name ;
this.Description =Description ;
this.Version =Version ;
}

Related

problem with deserializing XML into instances of Java objects

So I have a Spring Boot main() that queries an API that returns some XML (CRed and indented for your viewing pleasure)
<ns1:Entities xmlns:ns1="https://my.company.com/rest/model">
<ns1:Entity name="Model" href="..512971">
<ns1:Attribute name="id" type="Number" value="512971"/>
<ns1:Attribute name="modelNumber" type="String" value="4857395960"/>
</ns1:Entity>
</ns1:Entities>
that I want to deserialize into instances of class Model
public class Model implements java.io.Serializable {
private static final long serialVersionUID = -1234L;
#Id
#Column(name="id")
private Long id;
#Column(name="model_number")
private String modelNumber;
//constructors
public Model() {}
public Model( Long id, String num) {
this.id = id;
this.modelNumber = num;
}
public Model( String idStr, String num) {
this.id = Long.getLong(idStr);
this.modelNumber = num;
}
//getters and setters
public Long getId() {
return id;
}
public void setId( Long id) {
this.id = id;
}
public void setId( String idStr) {
this.id = Long.getLong(idStr);
}
....
}
and
#JsonIgnoreProperties(ignoreUnknown=true)
#JacksonXmlRootElement(localName="Attribute", namespace="ns1")
public class Attribute implements java.io.Serializable {
private static final long serialVersionUID = -5678L;
public String name;
public String type;
public String value;
//constructors
public Entity() {}
public Entity( String name, String type, String value) {
this.name = name;
this.type = type;
this.value = value;
}
//getters and setters
.....
}
and
#JsonIgnoreProperties(ignoreUnknown=true)
#JacksonXmlRootElement(localName="Entity", namespace="ns1")
public class Entity implements java.io.Serializable {
private static final long serialVersionUID = -9876L;
public String name;
public String href;
#JacksonXmlProperty(localName="Attribute")
#JacksonXmlElementWrapper(useWrapping=false)
private List<Attribute> list_attribute = new LinkedList<Attribute>();
//constructors
public Entity() {}
public Entity( String name, String href, List<Attribute> lisst) {
this.name = name;
this.href = href;
this.list_attribute = lisst;
}
//getters and setters
....
}
and
#JsonIgnoreProperties(ignoreUnknown=true)
#JacksonXmlRootElement(localName="Entities", namespace="ns1")
public class Entities implements java.io.Serializable {
private static final long serialVersionUID = -2345L;
#JacksonXmlProperty(localName="Entity")
#JacksonXmlElementWrapper(useWrapping=false)
private List<Entity> list_entity = new LinkedList<Entity>();
//constructors
public Entities() {}
public Entities( List<Entity> lisst) {
this.list_entity = lisst;
}
//getters and setters
public List<Entity> getList_entity() {
return list_entity;
}
public void setList_entity( List<Entity> lisst) {
this.list_entity = lisst;
}
....
}
So at last we get to a chunk of main()
HttpHeaders headers = new HttpHeaders();
headers.add( HttpHeaders.ACCEPT, MediaType.APPLICATION_XML_VALUE);
HttpEntity<Object> reqquest = new HttpEntity<Object>( null, headers);
ResponseEntity<String> responnse = this.restTemplate.exchange( "https://myendpointgoeshere.com", HttpMethod.GET, reqquest, String.class, 0);
Entities entities_obj = this.xmlMapper.readValue( xmlStr, Entities.class);
List<Model> list_model = Model.deserialize( entities_obj); // <--
throws
IAE - fld:id - type: + Number - value:512971
java.lang.IllegalArgumentException: Can not set java.lang.Long field ...Model.id to null
and yet
Model model_0 = list_model.get[0];
System.out.println( model_0);
does show a correctly populated instance of Model. So this is all mostly right but not 100% right. What am I doing wrong/not doing right? And there will be many kinds of Entity, Model being only one so Model should extend Entity ?
TIA,
Still-learning Steve

How do I go about creating the method?

I'm currently trying to create a class in java, to this specification:
I'm not sure how to create "ratings" since I'm seeing its using some
map function using the input of a string and an integer.
Here's my code so far:
public class Movie {
String ID;
String Name;
String Description;
String Genre[];
String Directors[];
String Actors[];
String Language;
String CountryOfOrigin;
}
Please create different objects for genre, director, actor and rating. It will be a best practice when you try to add more information to each entity.
Use access modifier "private" to each attribute and implement get,set methods as required.
Use ArrayLists instead of arrays to avoid resizing efforts when required.
import java.util.ArrayList;
import java.util.List;
public class Genre {
private int id;
private String name;
public Genre(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Director {
private int id;
private String name;
public Director(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Actor {
private int id;
private String name;
public Actor(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Rating {
private int value;
private String name;
public Actor(int value, String name) {
this.value = value;
this.name = name;
}
}
public class Movie {
private int id;
private String name;
private String description;
private List<Genre> generes;
private List<Director> directors;
private List<Actor> actors;
private String language;
private String countryOfOrigin;
pulic Movie(int id, String name, String description, String language, String countryOfOrigin){
this.id = id;
// set other variables
this.actors = new ArrayList<Actor>();
// create other lists
}
public void addGenere(Genre genere){
this.generes.add(genere);
}
// implement other add methods to lists
}

getter setter in inner private class in java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want to create bean in java corresponding to below json
{
"name": "",
"id": "",
"dept": {
"deptId": "",
"deptName": "",
"course": {
"courseId": "",
}
}
}
My idea is to create parent class and keep dept and course as inner private classes and then have getters setters to get or set data and form parent bean. But I am getting error "Change visibility to the public"
How can I access private fields of inner private class to get and set data?
try this way its will work
public class firstClass{
private String name;
private String id;
Department dept;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Department getDept() {
return dept;
}
public void setDept(Department dept) {
this.dept = dept;
}
}
class Department{
private int departId;
private String deptName;
Course course;
public int getDepartId() {
return departId;
}
public void setDepartId(int departId) {
this.departId = departId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
}
class Course{
private int courseId;
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
}
You can't access private fields. Why don't you create a getter and setter for the inner class private fields?
And, maybe you should consider using gson library.
You at least have to make say nested public interfaces, say Dept and Course, with your private (static) nested private classes DeptImpl and SourceImpl.
public class X {
public interface Dept { ... }
private static class DeptImpl extends Dept { ... }
public Dept getDept() { ... }
public Dept createDept(...) {
DeptImpl dept = new DeptImpl(...); ...
return dept;
}
Maybe you need to provide a factory method createDept.
In some cases the implementing class can be anonymous new Dept() { ... }.
You can use Builder Design pattern with immutable Objects:
public class Class {
private final String name;
private final int id;
private final Department dept;
private Class(ClassBuilder classBuilder){
this.name = classBuilder.getName();
this.id = classBuilder.getId();
this.dept = classBuilder.getDept();
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public Department getDept() {
return dept;
}
private static class Department{
private final int deptId;
private final String deptName;
private final Course course;
private Department(DepartmentBuilder departmentBuilder){
this.deptId = departmentBuilder.getDeptId();
this.deptName = departmentBuilder.getDeptName();
this.course = departmentBuilder.getCourse();
}
public int getDeptId() {
return deptId;
}
public String getDeptName() {
return deptName;
}
public Course getCourse() {
return course;
}
private static class Course{
private final int courseId;
private Course(CourseBuilder courseBuilder){
this.courseId = courseBuilder.getCourseId();
}
public int getCourseId() {
return courseId;
}
}
}
public static class ClassBuilder{
private final String name;
private final int id;
private final Department dept;
public ClassBuilder(String name, int id, Department dept){
this.name = name;
this.id = id;
this.dept = dept;
}
public Department getDept() {
return dept;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public Class build(){
return new Class(this);
}
}
public static class DepartmentBuilder {
private final int deptId;
private final String deptName;
private final Department.Course course;
public DepartmentBuilder(int deptId, String deptName, Department.Course course ){
this.deptId = deptId;
this.deptName = deptName;
this.course = course;
}
public int getDeptId() {
return deptId;
}
public String getDeptName() {
return deptName;
}
public Department.Course getCourse() {
return course;
}
public Department build(){
return new Department(this);
}
}
public static class CourseBuilder{
private final int courseId ;
public CourseBuilder(int courseId){
this.courseId = courseId;
}
public int getCourseId() {
return courseId;
}
public Department.Course build(){
return new Department.Course(this);
}
}
}
public class Sample {
public static void main(String ... strings){
Class clazz = new Class.ClassBuilder("ClassName", 1, new Class.DepartmentBuilder(1, "departmentName", new Class.CourseBuilder(2).build()).build()).build();
System.out.println(clazz.getDept());
}
}

In Spring mvc How to add add set values to mysql

My goal :
In Spring MVC I have to save mobile phone contact list into database.
example:
phone1 sonia 2554654 work
2554654 home
multiple phone_number with multiple phone_Number type
contacts table
id,
contact_name
phone_number
phone_type
in my java class I have
public class ContactMobile {
private String type;
private String number;
public ContactMobile() {
}
public ContactMobile(String type, String number) {
super();
this.type = type;
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
and here I use SET for phone number and type
#Entity
#Table(name = "_contact")
public class MobileContact {
private String id;
private String fullname;
private Set<ContactMobile> mobileNumbers;
public MobileContact(String fullname, Set<ContactMobile> mobileNumbers) {
super();
this.fullname = fullname;
this.mobileNumbers = mobileNumbers;
}
#Id
#Column(name = "Id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "fullname")
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public Set<ContactMobile> getMobileNumbers() {
return mobileNumbers;
}
public void setMobileNumbers(Set<ContactMobile> mobileNumbers) {
this.mobileNumbers = mobileNumbers;
}
public MobileContact() {
super();
}
}
I am using hibernate to store data..
my question is in my MobileContact class in
public Set<ContactMobile> getMobileNumbers() {
return mobileNumbers;
}
what annotation I have to use here to save multiple phonenumbers?
The MobileContact entity has many ContactMobile, it is a OneToMany relation. In your ContactMobile table, you should has a field for the id of MobileContact, like mobile_contact_id, and set the join column on that field as below in your ContactMobile:
#OneToMany(fetch = FetchType.LEZY)
#JoinColumn(name = "mobile_contact_id")
private Set<ContactMobile> mobileNumbers;
You can get the detail about the relation in this.
You can use the Embeddables (instead of Entities) for very simple value objects like MobileContact (then they do not need an ID, and the are no just simple value objects without own identity)
#Embeddable
public class ContactMobile {...
//implement an equals and hashcode method!
}
public class MobileContact {
...
#ElementCollection
private Set<ContactMobile> mobileNumbers;
...
}
#See Java Persistence/ElementCollection

Altering a Class to create a list

I need to update my Country class so that it can store a list of languages, I also need a field for the list, a getter, and a method that allows me to add a language to the collection. I very green when it comes to programing. This is what I have so far.
public class Country {
private int id;
private String name;
private long population;
private double medianAge;
private List<String> languages;
List<String> list = new ArrayList<>();
/**
* Create a Country object with the given properties
*/
public Country(int id, String name, long population, double medianAge) {
this.id = id;
this.name = name;
this.population = population;
this.medianAge = medianAge;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public long getPopulation() {
return population;
}
public double getMedianAge() {
return medianAge;
}
}
You can remove the member list - cannot see a reason for you to have it.
You constructor can be:
public Country(int id, String name, long population, double medianAge) {
this.id = id;
this.name = name;
this.population = population;
this.medianAge = medianAge;
this.languages = new ArrayList<>();
}
Then you can have a method to add a language to the list:
public void addLanguage (String language) {
languages.add(language);
}
Finally a method to return the list of languages as given below:
public List<String> getLanguages() {
return languages;
}
More information on how ArrayList works
You need a getter method to access languages like below
getLanguages(){
return this.languages;
}
And a method which ads one language to existing list.
addLanguageToList(String language){
this.getLanguages().add(language);
}
Do you mean you want to add an initializer for languages? You can use the list.add() method.
public class Country{
private int id;
private String name;
private long population;
private double medianAge;
private ArrayList<String> languages = new ArrayList<String>();
public Country(int id, String name, long population, double medianAge String language) {
this.id = id;
this.name = name;
this.population = population;
this.medianAge = medianAge;
this.languages.add(laguage);
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public long getPopulation() {
return population;
}
public double getMedianAge() {
return medianAge;
}
}
Its very simple, Create a getter and two add method, one for adding one language and another add method for adding list of language to existing language list.
import java.util.ArrayList;
import java.util.List;
public class Country {
private int id;
private String name;
private long population;
private double medianAge;
private List<String> languages;
List<String> list = new ArrayList<>();
/**
* Create a Country object with the given properties
*/
public Country(int id, String name, long population, double medianAge) {
this.id = id;
this.name = name;
this.population = population;
this.medianAge = medianAge;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public long getPopulation() {
return population;
}
public double getMedianAge() {
return medianAge;
}
public List<String> getLanguages() {
return languages;
}
public void addLanguage(String language) {
this.languages.add(language);
}
public void addLanguages(List<String> languages) {
this.languages.addAll(languages);
}
}

Categories