Reputation: 13
I dont know how to really ask this. But like...
Student stud1 = new Student("Shady");
Student stud2 = new Student("Nick");
Student stud3 = new Student("Name");
stud2.addBook(new Book(Book.BOOK_MISERABLES, 3););
Now if we assume we have the following variable in the Book class:
private Student owner;
And now the question, inside the constructor of "Book" -> Is it possible to get the "stud2" object it's being called to? Without adding an additional parameter to the constructor? If so, how? I think it's possible... So it will be something like this:
private Student owner;
public Book(int bookNum, int weeks){
this.owner = this.GET_THE_TARGET_THIS_IS_CALLED_ON;
this.bookNumber = bookNum;
this.time = weeks;
}
Upvotes: 1
Views: 49
Reputation: 2031
What you're asking is not directly possible. You will need to either
Student
instance to your Book
constructoror
Book
class to set the value of the owner
field to your Student
instance.The latter would be a method that looks like this:
public void setOwner(Student owner) {
this.owner = owner;
}
Additionally, you may want to modify your Student.addBook
method to call this setter, like this:
book.setOwner(this);
As you mentioned in your comment, you can traverse the stack using Thread.currentThread().getStackTrace()
However, you'll be unable to obtain an object reference using that technique. You can obtain the class
or method
name but the uses for that are limited unless you intend to construct a new instance. That's all highly unorthodox and not at all appropriate for this situation.
Upvotes: 4