开发者

How to create object of class

I think this explains my question well enough:

public class Model {
    public static Model [] findAllBySQL(String SQL){
        //this is simplified.  It should really query the DB and then fill model(s) with the DB values, and return the model(s).  sql query can return more than one row
        return new this(); //sytax error here
    }
}


public class UserModel extends Model {

}


UserModel.findAllBySQL("firstname=john") //How do I design the above so this returns a UserModel object?

I'm relatively new to Java. My background is mostly PHP. I am trying to create a simple home-made active record system.. I know this is recreating the wheel, but that's how I learn :)

EDIT: Most of you 开发者_如何学JAVAguys misunderstood me. I know how to simple to new UserModel(). I changed the code to make it more clear.


You should use a constructor:

public class Model {
    //Constructor
    public Model()
    {
    // Do initialization stuff here
    }
}


public class UserModel extends Model {
    //Constructor
    public UserModel()
    {
    // Do initialization stuff here
    }
}

To create new object, you call it like that:

UserModel myUserModel;    // Declare new object reference
myUserModel = new UserModel();   // create new object of this class

Edit:

If you declare the method as a method returning array of Models, you can't return a single model, you may return a Model array with one Model, but not a single object.

For example

public static Model [] findAllBySQL(String SQL){
    // find how many models do you have
    Model[] models = new Model[numberOfModels];
    for (Model model : models)
    {
         model = new Model();
         //do what you want with it...
    }
    return models; //sytax error here
}


Why not simply use new operator as

UserModel userModel = new UserModel();

To know different ways to create an object in java see this thread: what-are-all-the-different-ways-to-create-an-object-in-java


Edit

Based on your edit what you can do is?

public static Model findBySQL(String SQL){
        Model model = new Model();
        // Now query in db to get data. then use setter methods of Model to set data in object
        // i.e. model.setXXX(XXX);
        // and finally return that model object.
        return model;
    }

Edit 2

UserModel could have getFullName() which concatenates the first name with the last name from the db. I would need to be able to access this method straight away on the object returned from findBySQL

You can try like this: in UserModel,

public String getFullName(){
    Model model = findBySql("str='str'");
    return model.getFirstName()+"  "+model.getLastName();
}


Sounds like you need the Factory Method Pattern. If you have a Model super class and several types of Models then you can encapsulate the object creation in a ModelFactory class with a createModel() method that returns the appropriate type of Model based on the parameter to the method.

 class ModelFactory(){
       public Model createModel(String sql, String type){
            //execute SQL

            if(type.equals("user")){
                 UserModel model = new UserModel();
                 //set the attributes here
                 return model;
            }

            if(type.equals("other")){
                 OtherModel model = new OtherModel();
                 //set attributes here
                 return model;
            }

             //etc
       }
 }

To actually get a Model object you can now:

       ModelFactory factory = new ModelFactory();
       Model m = factory.createModel("select * from mytable", "user");


This is how you use this

UserModel m = new UserModel();

UserModel m now has all functions/values from
UserModel + the functions/values from Model.

Example

public class Model {
    public Model()
    {
    // Do initialization stuff here
    }

    public getVal(){
        return 1+1;
    }
}


public class UserModel extends Model {
    public UserModel()
    {
    // Do initialization stuff here
    }

    public getValue2(){
        return 2+2;
    }
}


UserModel m = new UserModel();

m.getVal(); //Will return 2
m.getValue2(); // Will return 4


You can do it in this way :

import java.util.ArrayList;
import java.util.List;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

public class Generics<T> {

    //method that returns a generic list
    public List<T> findAllBySQL(String SQL) {
        throw new NotImplementedException();
    }

    public static void main(String[] args) {
        //base class that returns a list of childs
        Generics result = new ExtendedGenerics(null);
        List<ExtendedGenerics> genericArray = result.findAllBySQL(null);
        for (ExtendedGenerics item : genericArray) {
            System.out.println(item);
        }
    }
}

//extend base class and specify generic type
class ExtendedGenerics extends Generics<ExtendedGenerics> {

    private String myMessage;

    public ExtendedGenerics(String yourMessage) {
        myMessage = yourMessage;
    }

    @Override
    //overriding base method, so it return a instances list of this class 
    public List<ExtendedGenerics> findAllBySQL(String SQL) {
        ArrayList<ExtendedGenerics> result = new ArrayList<ExtendedGenerics>();
        result.add(new ExtendedGenerics("I am first"));
        result.add(new ExtendedGenerics("I am second"));
        result.add(new ExtendedGenerics("I am third"));
        return result;
    }

    @Override
    public String toString() {
        return "ExtendedGenerics{" + myMessage + '}';
    }
}

So in this way no casting in necessary. This is the output of the code :

ExtendedGenerics{I am first}
ExtendedGenerics{I am second}
ExtendedGenerics{I am third}


You can use Factory Method plus Java Generics:

public class Model {
  public static <T> T[] findAllBySQL(String SQL, Class<T extends Model> type) {
    T[] result = new T[123];
    for (int i = 0; i < 123; i++) {
      result[i] = type.newInstance();
    }
    return result;
  }
}
public class UserModel extends Model {
}
Model[] rowset = UserModel.findAllBySQL("firstname=john", UserModel.class); 

I assume this is the alternative of a plain simple PHP construct:

new $type();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜