Hello is there a possibility to pass all nulls to constructor and have correctly new object created?
Lets say I have such class:
public class MobileDataReportSearchCriteria extends BaseSearchCriteria<MobileDataReport> {
private Date reportDateFrom;
private Date reportDateTo;
private long opponentStationId;
private boolean correctness;
public MobileDataReportSearchCriteria() {
}
public MobileDataReportSearchCriteria(Date reportDateFrom, Date reportDateTo, long opponentStationId, boolean correctness) {
this.reportDateFrom = reportDateFrom;
this.reportDateTo = reportDateTo;
this.opponentStationId = opponentStationId;
this.correctness = correctness;
}
}
and now I want to instantiate new object of this class with new MobileDataReportSearchCriteria(null, null, null, null); because those objects in business logic could be nulls. How to do that because when I do that I get NullPointerException. Thank you in advance!
Related
Guys please tell me what is the construction when I call method while creating an object?
for example: Person p = new Person().get.....
If you want to create an Instance of the Object with new and call the Method while creating that Object than you can call that Method in the Constructor of that Objects Class
class Person {
Person() {
method();
}
}
If you create your Object (Person) with this constructor the Method will be invoked.
If you want to call a Method after creating the Object.
Person person = new Person();
String name = person.getName();
or
String name = new Person().getName();
I guess patter Builder is what are you looking for
public class Computer {
//required parameters
private String HDD;
private String RAM;
//optional parameters
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;
public String getHDD() {
return HDD;
}
public String getRAM() {
return RAM;
}
public boolean isGraphicsCardEnabled() {
return isGraphicsCardEnabled;
}
public boolean isBluetoothEnabled() {
return isBluetoothEnabled;
}
private Computer(ComputerBuilder builder) {
this.HDD=builder.HDD;
this.RAM=builder.RAM;
this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled;
this.isBluetoothEnabled=builder.isBluetoothEnabled;
}
Computer comp = new Computer.ComputerBuilder(
"500 GB", "2 GB").setBluetoothEnabled(true)
.setGraphicsCardEnabled(true).build();
The closest thing that comes to mind may be singleton, but it doesn't create new objects. Person p = Person().getInstance()?
I have this class and need to know which constructor is needed to create an object that may immediately use all its methods without error
public class Robot {
private boolean fuelEmpty = true;
private int roboID;
private String greeting;
private String securityProtocol;
//insert robot constructor here
public void destroyAllHumans(){
while (fuelEmpty == false) {
//robot begins to destroy all humans
}
}
public int getRoboID(){
return roboID;
}
public void greet(){
System.out.println(greeting);
}
public void setSecurityProtocol(String proto){
securityProtocol = proto;
}
}
For example should look like this:
public Robot(int id, String greet) {
roboID = id;
greeting = greet;
}
or this:
public Robot(int id, String greet) {
roboID = id;
greeting = greet;
fuelEmpty = false;
}
or:
public Robot(boolean full, int id, String greet, String proto) {
roboID = id;
greeting = greet;
fuelEmpty = full;
securityProtocol = proto;
}
Which of these (or something else different) is needed so that all the other methods can run without an error?
You can overload the constructor as much as you need, the important thing is
the object gets properly instantiated after you create a new one...
a way can be:
public Robot() {
this(false, 0, "", "");
}
public Robot(int id) {
this(false, id, "", "");
}
public Robot(boolean fuelEmpty, int roboID, String greeting, String securityProtocol) {
this.fuelEmpty = fuelEmpty;
this.roboID = roboID;
this.greeting = greeting;
this.securityProtocol = securityProtocol;
}
so look how all other constructors will at the end call internally the
public Robot(boolean fuelEmpty, int roboID, String greeting, String securityProtocol)
that will give you the waranty that no matter which constructor is invoked, the Robot is fully created and can invoke all those methods without crashing
The solution works like this:
you look at each of your methods
you check which fields each method is using
you check more closely, if the method breaks when that field has its default value (like null for Objects, or false for booleans)
When you do that for all methods, you get a list of those fields that you need to initialize somehow. Then you could go forward and define a corresponding constructor.
But of course, that is the wrong approach.
The real answer goes like this: you don't put fields into a class because you can. You add them because they are required so that this class can implement the requirements (responsibilities) that you want it to implement. Meaning: you focus on the methods that your class should provide. Then you clarify which fields you need in order to implement these methods.
In other words: you have exactly those fields in your class that your class needs. If you have fields in there that go unused - then you get rid of them.
I would like to make a generic method to get a List from the parameter object.
The problem is because I have a declared object with a instance of the other class that extends the declared class.
I don't want to use the instanceof solution because the number of classes that extends LimitedValue can be big.
I thought to use reflection for a solution, but I don't know how to use that with an instance of object, in this part of the code:
Class cls = Class.forName(limitedValue.getClass().getName());
Object obj = cls.newInstance();
//This is wrong, I don't want a new instance.
Method[] methods = cls.getDeclaredMethods();
for(int x= 0; x < methods.length; x++) {
Method method = methods[x];
if ("java.util.List".equals(method.getReturnType().getName())) {
//How to get the value of this method from limitedValue instance ?
}
}
This is my full code:
public class CalculatorLimitedValue {
public static void main(String[] args) throws Exception {
StoreItem storeItem = new StoreItem(1L, "Name of StoreItem", 50L);
List listOfStoreItems = new ArrayList();
listOfStoreItems.add(storeItem);
LimitedValue limitedValue0 = new Store(listOfStoreItems);
List firstList = calculator(limitedValue0);
//do something with the list
SupermarketItem supermarketItem = new SupermarketItem(1L, "Name of SupermarketItem", 21L);
List listOfSupermarketItems = new ArrayList();
listOfSupermarketItems.add(supermarketItem);
LimitedValue limitedValue1 = new Supermarket(listOfSupermarketItems);
List secondList = calculator(limitedValue1);
//do something with the list
}
/** This is the method that I'd like to make generic to return a List */
private static List calculator(LimitedValue limitedValue) throws Exception{
Class cls = Class.forName(limitedValue.getClass().getName());
Object obj = cls.newInstance();
//This is wrong, I don't want a new instance.
Method[] methods = cls.getDeclaredMethods();
for(int x= 0; x < methods.length; x++) {
Method method = methods[x];
if ("java.util.List".equals(method.getReturnType().getName())) {
//How to get the value of this method from limitedValue instance ?
}
}
/* I don't want to use this one way, because my classes that extends LimitedValue
can be big. I would like to made a generic way to get de list of classes. */
if (limitedValue instanceof Store) {
System.out.println("This is a store");
return ((Store) limitedValue).getStoreItems();
} else if (limitedValue instanceof Supermarket) {
System.out.println("This is a supermarket");
return ((Supermarket) limitedValue).getSupermarketItems();
}
return null;
}
}
If it help, these are my other classes:
LimitedValue.class
public class LimitedValue { }
StoreItem.class
public class StoreItem {
private Long id;
private String nameOfStoreItem;
private Long valueOfStoreItem;
public StoreItem(Long id, String nameOfStoreItem, Long valueOfStoreItem){
this.id = id;
this.nameOfStoreItem = nameOfStoreItem;
this.valueOfStoreItem = valueOfStoreItem;
}
//getters and setters...
}
SupermarketItem.class
public class SupermarketItem {
private Long id;
private String nameOfSupermarketItem;
private Long valueOfSupermarketItem;
public SupermarketItem() {
}
public SupermarketItem(Long id, String nameOfSupermarketItem, Long valueOfSupermarketItem) {
this.id = id;
this.nameOfSupermarketItem = nameOfSupermarketItem;
this.valueOfSupermarketItem = valueOfSupermarketItem;
}
//getters and setters...
}
Store.class
public class Store extends LimitedValue {
private List<StoreItem> storeItems;
public Store(List<StoreItem> storeItems) {
this.storeItems = storeItems;
}
//getters and setters
}
Supermarket.class
public class Supermarket extends LimitedValue {
private List<SupermarketItem> supermarketItems;
public Supermarket(List<SupermarketItem> supermarketItems) {
this.supermarketItems = supermarketItems;
}
//getters and setters
}
You could try to use reflection here to try to achieve what you want, but it would be better to reconsider your overall design and try to use a better object oriented design that solves the problem at hand.
In particular, lets say we consider adding a method called getItems to the LimitedValue class that returns a List of items, which may be SupermarketItems or may be StoreItems. If it is structured correctly, you won't need to know the actual type because the code will be abstracted over it polymorphically.
public abstract class LimitedValue {
List<? extends Item> getItems();
}
We've now defined a new method on LimitedValue, but we also have to consider that we've introduced this new Item thing. I note that the SupermarketItem and StoreItem all share similiar attributes, name, id and value, so it seems that it might be possible to use a single class to represent them all.
public abstract class Item {
final Long id;
final String name;
final Long value;
public Item(final Long id, final Long name, final Long value) {
this.id = id;
this.name = name;
this.value = value;
}
String getName() {
return name;
}
// other getters and setters
}
public class SupermarketItem extends Item {
public SupermarketItem(final Long id, final Long name, final Long value) {
super(id, name, value);
}
}
public class StoreItem extends Item {
public StoreItem(final Long id, final Long name, final Long value) {
super(id, name, value);
}
}
Now we've completely abstracted away the need for any reflection when accessing these objects - you can simply call item.getValue() as you will know that every item in the list is of type Item.
Of course, you'll also need to refactor the Store and SuperMarket classes, for example:
public class Supermarket extends LimitedValue {
private List<SupermarketItem> supermarketItems;
public Supermarket(List<SupermarketItem> supermarketItems) {
this.supermarketItems = supermarketItems;
}
public List<? extends Item> getItems() {
return supermarketItems;
}
}
and because you are only returning a List<Item> you always know what is in it, and you can change your main code to work with this.
This is a much cleaner long term solution.
To get the List value, use Method#invoke:
List list = method.invoke(limitedValue);
You don't need Object obj = cls.newInstance(); - you're not using it at all in the method.
In any case, you're making it very difficult for yourself. You could also define an interface
public interface HasList<E> {
List<E> getList();
}
and have all classes implement this.
I have created following singleton design pattern in my java program
private int OwnerId;
private String OwnerName;
private String OwnerNic;
private String OwnerAddress;
private int OwnerTele;
private String OwnerEmail;
private String OwnerDate;
private static OwnerML instance = new OwnerML();
// make the coosntructor private so that this class cannot be instantiated
private OwnerML(){}
// get the only object available
public static OwnerML getInstance() {
return instance;
}
public int getOwnerId() {
return OwnerId;
}
public void setOwnerId(int OwnerId) {
this.OwnerId = OwnerId;
}
I have used a separate method to call the view method
public ArrayList<OwnerML> SelectOwnerData()
{
ArrayList<OwnerML> OwnerList = new ArrayList<OwnerML>();
try {
Connection con = DB.connect();
String selectQ = "select * from owners";
PreparedStatement ps2 = con.prepareStatement(selectQ);
ResultSet rs = ps2.executeQuery();
while (rs.next())
{
OwnerML OwnerData =OwnerML.getInstance();
OwnerData.setOwnerId(rs.getInt(1));
OwnerData.setOwnerName(rs.getString(2));
OwnerData.setOwnerNic(rs.getString(3));
OwnerData.setOwnerAddress(rs.getString(4));
OwnerData.setOwnerTele(rs.getInt(5));
OwnerData.setOwnerEmail(rs.getString(6));
OwnerList.add(OwnerData);
}
rs.close();
ps2.close();
con.close();
By using following method I'm calling it in my interface
ArrayList<OwnerML> ownerList = new OwnerCL().SelectOwnerData();
Object obj[][] = new Object[ownerList.size()][6];
int x = 0;
for (OwnerML t : ownerList) {
obj[x][0] = t.getOwnerId();
obj[x][1] = t.getOwnerName();
obj[x][2] = t.getOwnerNic();
obj[x][3] = t.getOwnerAddress();
obj[x][4] = t.getOwnerTele();
obj[x][5] = t.getOwnerEmail();
x++;
}
ownerTbl.setModel(new javax.swing.table.DefaultTableModel(obj,new Object[]{
"OwneID", "Name", "Nic", "Address", "Tele", "Email", "Date", "VehicleID", "Type", "Model", "Year", "RegNumber"
}));
The problem I am facing at the moment is that it always repeats the data in the last row.
I would be very thankful if anyone could help me with this.
There is one mayor flaw in your design.
I guess OwnerML class is supposed to be the container for the data. It does not make sense to implement it as a Singleton.
Every time you call OwnerML.getInstance() while populating the OwnerList list with results from the database, you are referencing the same class' instance (it's the very nature of Singleton).
As a result you will always have a list with multiple references to the same object (singleton).
You should forget about using Singleton as a data container (let's call it Data Transfer Object - DTO).
In fact Singleton is rarely useful for anything (notably exceptions are: logging subsystem, handler of singular hardware resource, and maybe Spring-ish bean factory).
In short:
make the OwnerML constructor public and then replace
OwnerML OwnerData =OwnerML.getInstance();
with
OwnerML OwnerData = new OwnerML();
===EDIT===
#Anton 's comment was first, and he's right. I should type faster next time :)
I'm using ORMLite, trying to use the ForeignCollectionKey but I got the following error :
Internal DAO object is null. LazyCollections cannot be used if they have been deserialized.
I've my object named Zone :
public class Zone implements Serializable {
private static final long serialVersionUID = 1L;
public static final String ZONE_ID = "id";
public static final String ZONE_PARENT_ID = "parentZoneId";
#DatabaseField(generatedId=true)
private int id;
#DatabaseField()
String name;
#DatabaseField(foreign=true, foreignAutoRefresh = true)
Zone parentZone;
#ForeignCollectionField(foreignFieldName = "parentZone", eager = true)
private ForeignCollection<Zone> zoneChild;
public Zone() {
// TODO Auto-generated constructor stub
}
public ForeignCollection<Zone> getZoneChild() {
return zoneChild;
}
public void setZoneChild(ForeignCollection<Zone> zoneChild) {
this.zoneChild = zoneChild;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
In a class i'm doing a recursive method to get all my zone child objects :
public void getZone(Zone zone, Dao<Zone, Integer> tempZoneDao){
ZoneListEntity zoneEntity = new ZoneListEntity();
zoneEntity.setName(zone.getName());
zoneEntity.setNiveau(0);
zoneEntity.setZone(zone);
mainZoneList.add(zoneEntity);
List<Zone> childList = new ArrayList<Zone>(zone.getZoneChild());
//set rootZone's children as ZoneListEntity
for(Zone currentZone : childList){
ZoneListEntity zoneGroup = new ZoneListEntity();
zoneGroup.setName(currentZone.getName());
zoneGroup.setZone(currentZone);
System.out.println("Zone : "+currentZone.getName());
getZone(currentZone, tempZoneDao);
}
}
When i'm entering for the first time in my getZone, everything going well. Then when I loop in getZone the application crashes trying to access to the child zone :
List<Zone> childList = new ArrayList<Zone>(zone.getZoneChild());
Do you have any ideas ? Is my model construction right ?
Thanks
Do you have any ideas ? Is my model construction right ? Thanks
So the exception message is trying to explain what is going on. I'm not sure how it can be improved.
Internal DAO object is null. LazyCollections cannot be used if they have been deserialized.
You are trying to access zoneChild which is a ForeignCollection that has been deserialized. Since it has been deserialized all of the underlying database configurations and connections could not be reestablished. I guess this can happen when it stored in an Android Bundle? I'm not sure if this is the only case.
If you need to get the Zone children you are going to have to either call dao.refresh() on the entity after you deserialize it or do the query yourself by doing the zoneDao.
I solved this problem like Gray suggested: pass the primary key attribute in the Bundle and then obtain the object again from the database in the destination Activity:
Example:
Let's suppose I want to pass a Person object and that I've declared Person.name as:
#DatabaseField (columnName ="name")
private String name;
Then:
ActivityA
Intent intent = new Intent(ActivityA.this, ActivityB.class);
Bundle bundle = new Bundle();
bundle.putString("NAME" Person.getName());
intent.putExtras(bundle);
ActivityB
String name = getIntent().getExtras().getString("NAME"));
Person p = getHelper().getPersonDao().queryForEq("name", name);
And there you are, your Collection will be refreshed.