aki
aki

Reputation: 1761

excute method whenever object is created

I would like to know how to execute method, in java, whenever object is created.

for example:

public class Person {
    private String name;
    private int age;
    private Date dateCreated;

    public setName(String name){
    ...
    }
    ... some other methods ...

    public setDateCreated(){
         this.dateCreated = new Date();
}

I would really like for my setDateCreated() method to be executed on every object when it is created.

Upvotes: 0

Views: 146

Answers (4)

duffymo
duffymo

Reputation: 308753

You realize, of course, that this class breaks the Java Bean standard as coded.

The standard will expect to see a Date object passed to the setDateCreated() method:

public void setDateCreated(Date newDate) { 
    this.dateCreated = ((newDate == null) ? new Date() : new Date(newDate.getTime()));
}

You're free to do it your way, once you add a void return type, but don't be shocked if other code that expects you to conform to the standard complains.

Upvotes: 1

hburde
hburde

Reputation: 1441

I would use some sort of aspect oriented approach - that way you avoid having the code in your class. Check aspect j or spring for aspect oriented programming.

Upvotes: -1

Simiil
Simiil

Reputation: 2311

use Constructors:

public Person(){
  setDateCreated();
}

also, public class Person(){ should be public class Person{

Upvotes: 2

talnicolas
talnicolas

Reputation: 14053

Just call setDateCreated in your object constructor:

 public Person(){
     setDateCreated();
 }

You could also do it directly in the constructor if you don't want it to be modified later:

 public Person(){
     this.dateCreated = new Date();
 }

Upvotes: 10

Related Questions