How can I get the class object from its member variable? - java

I'm currently working on this code, I want to pass an ID to a member function to get the object.
public class Car {
private int _ID;
private String name;
private String model;
Car(int _id, String name, String model){
this._ID = _id;
this.name = name;
this.model = model;
}
....
public static Car getCar(int _id){
Car mCar;
//TODO: Algo to get car
return mCar;
}
}
Is there any way I can get the object in this way?
Any help is appreciated!
Thank You!

You'll need to keep a Map of objects by key. Here's one way to do it:
public class Car {
private int _ID;
private String name;
private String model;
Car(int _id, String name, String model){
this._ID = _id;
this.name = name;
this.model = model;
carsById.put(_id, this); // <-- add to map
}
....
private static Map<Integer, Car> carsById = new HashMap<>();
public static Car getCar(int _id){
return carsById.get(_id);
}
}

There's no predefined way to do that. You'd have to have Car or something else maintain a Map<Integer,Car> or similar of cars. This would usually be best done not in Car itself, but in the code using it.

Unless you have a list (or map or tree or anything else suitable) of created Car, it's not possible with your current code only. A good practice is to separate this list out of Car class, maintained elsewhere. But if you insist, shmosel provides one way.

Related

How can I get the composite field column in Java mission control's event browser?

I am able to see the primitive data type used in java class in the event browser's table of Java Mission Control. But it is not showing the composite data types.
My code is:
package com.foo.bar;
public class AB {
#Name("com.foo.bar.Author")
#Label("Author Event")
public static class Author extends Event {
String authorName;
int age;
String place;
Author(String name, int age, String place)
{
this.authorName = name;
this.age = age;
this.place = place;
}
}
#Name("com.foo.bar.Book")
#Label("Book Event")
public static class Book extends Event
{
String name;
int price;
// author details
Author auther;
Book(String n, int p, Author auther)
{
this.name = n;
this.price = p;
this.auther = auther;
}
}
public static void main(String[] args) throws InterruptedException {
Author author = new Author("John", 42, "USA");
Book b = new Book("Java for Begginer", 800, author);
b.begin();
author.begin();
author.commit();
b.commit();
}
}
And I am getting something like this in JMC:
How can I get the Author details in Book event? Is there a way in JMC to get the composite data in event browser's column?
Thanks
You don't. You relate the events to each other. I.e. the author event and the book event should probably both have an authorId in them.
See, for example, how the gc id is used to relate garbage collection related events to each other.
Jave events can't store composite data in fields, but you can link events together as suggested by Hirt.
#MetadataDefinition
#Name("com.example.BookAuthor")
#Label("Book Author")
#Relational
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.FIELD})
public #interface BookAuthor {
}
#Name("com.example.Author")
#Label("Author")
public class Author extends Event {
#Label("Author");
String authorName;
#Label("Age");
int age;
#Label("Place");
String place;
#Label("Author ID");
#BookAuthor
long id;
}
#Name("com.example.Book")
#Label("Book")
public class Book extends Event {
#Label("Name")
String name;
#Label("Price")
int price;
#Label("Author ID")
#BookAuthor
long authorId;
}
JDK Mission Control GUI, as of today, won't group them together, but that is how a relation is expressed.

How to Construct an Object with an Arraylist as Parameter?

I want to implement a class for Museum objects.
Each museum Has a name and can contain different Art objects.
Art Objects are implemented within another class
Each Art Object has 3 attributes (name, artist, value)
class Pieces_of_art {
private String name;
private String artist;
private float value;
Pieces_of_art(String name, String artist, float value) {
this.name = name;
this.artist = artist;
this.value = value;
}
}
class museum {
Arraylist<Pieces_of_art> set = new ArrayList<>();
//Initializing Arraylist with type "Piece_of_art" called set and it's empty?
String name;
museum(String name, Arraylist<Pieces_of_art> set) {
this.name = name;
set = new ArrayList<Piece_of_art>();
}
}
I don't really understand how it is possible to use and arraylist within a constructor as an empty parameter
There seems no hard to understand. Constructor is a special kind of method. As a method, why not take a List as parameter?
By the way, in your case, you have initialized set parameter already. If you want to make use of it. try below
museum(String name, Arraylist<Pieces_of_art> set) {
this.name = name;
this.set.addAll(set);
}

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

Generics in POJO - Is this a good practice

I have a Base Class.
#Data
class BaseDocument{
String id;
String name;
//Other fields
}
Say I have many classes that extends BaseDocument one below.
class NoteDocument extends BaseDocument{
String description;
Long lastModifiedDate;
//etc
}
It does not make sense to me to send entire document to UI in some cases. Most of the cases I need only id and name.
So for every document I have a VO class.
#Data
class BaseVO {
private String id;
private String name;
}
#Data
class NoteVO extends BaseVO{
//Nothing here now
}
And in NoteDocument I have.
public NoteVO getVo(){
Assert.notNull(getId());
NoteVO noteVo = new NoteVO();
noteVo.setName(getName());
noteVo.setId(getId());
return noteVo;
}
Now I have to copy this method in all the classes that extends BaseDocument.
Instead, I changed my BaseDocument like below.
#Data
class BaseDocument<V extends BaseVO>{
String id;
String name;
public V getVo(Class className) {
Assert.notNull(getId());
V vo = null;
try {
vo = (V) className.newInstance();
vo.setName(getName());
vo.setId(getId());
} catch (IllegalAccessException|InstantiationException e){
e.printStackTrace();
}
Assert.notNull(vo);
return vo;
}
}
I am new to generics. My first question, is this a good practice. Are there any problems in using reflection to create instance, any performance issues? Is there any better way to do achieve (write less code) this.
Edit: Suppose I need to display note in UI, Along with note I need to display name of the User who created note. I am using mongodb, when I save the note I also save UserVO in note, which will have user id and name of the user. If I save only user id while saving the note, I will have to do one more query to get the name of user while displaying. I want to avoid this.
Do not use reflection; use inheritance and maybe covariant return types instead. It will be faster, clearer, more precise, and easier to maintain. You may also find it useful to add methods to populate your VOs incrementally. I didn't come up with a clean way to apply generics to this situation, but I don't think you need them:
class BaseVO {
String id;
String name;
void setId(String id) {
this.id = id;
}
void setName(String name) {
this.name = name;
}
}
class NoteVO extends BaseVO {
// ...
}
#Data
class BaseDocument {
String id;
String name;
//Other fields
protected void populateBaseVO(BaseVO vo) {
vo.setId(id);
vo.setName(name);
}
public BaseVO getVO() {
BaseVO vo = new BaseVO();
populateBaseVO(vo);
return vo;
}
}
#Data
class NoteDocument extends BaseDocument {
String description;
Long lastModifiedDate;
// ....
protected void populateNoteVO(NoteVO vo) {
populateBaseVO(vo);
// ...
}
public NoteVO getVO() {
NoteVO vo = new NoteVO();
populateNoteVO(vo);
return vo;
}
}

Adding data to an array list

I'm working on an Android project and I'm trying to make use of an ArrayList which is of type MyClass. I am trying to store data in the ArrayList to each of the variables within MyClass. Below is the code I am using.
Below is the Class with the variables that will be used.
class SearchData
{
public int id;
public String category;
public String company;
public String loginAction;
public String username;
public String password;
public String type;
public String appName;
}
Below is how I am initialising the ArrayList
ArrayList<SearchData> passwords = new ArrayList<SearchData>();
And below is how I am trying to add new data to the ArrayList
passwords.add(new SearchData()
{
});
I can't figure out how to then set the variables from within the class with the data that I need them to be set to. In C#, which I know more about than Java, I can do the following:
passwords.add(new SearchData()
{
id = 0,
category = "hello"
});
However, I'm not seeing any of the variables that are within the class being shown in the Intellisense help.
What am I doing wrong?
You need to create an object and set all the attributes first, and then add it to the List: -
SearchData searchData = new SearchData();
searchData.setId(1);
searchData.setCategory(category);
...
passwords.add(searchData);
Create a constructor for your class.
class SearchData
{
public int id;
public String category;
public String company;
public String loginAction;
public String username;
public String password;
public String type;
public String appName;
SearchData(int id, String category, String company......){
this.id = id;
this.category = category;
this.company = company;
...
}
}
Then use it like this:
passwords.add(new SearchData(0,"Category1", "Company1"......));
Create an object and store reference to it:
SeachData searchData = new SearchData();
Set the properties you want to set:
searchData.setId(123);
...so on
searchData. Ctrl+Space should show the intellisense now..
Adding the search reference to the list:
list.add(searchData);
SearchData sd = new SearchData();
sd.id = 0;
sd.category = "hello";
passwords.add(sd);

Categories

Resources