This question already has answers here:
Java: How to listen on methods invocation without registering each object explicitely?
(3 answers)
Listener on Method.invoke java
(1 answer)
Closed 3 years ago.
I have a class Person and I'd like to be aware of every call to getFirstName() method:
public class Person {
private String firstName;
private String lastName;
public Person() {...}
public String getFirstName() {
return this.firstName
}
//... Rest of getters and setters
}
So when somebody does this, I'd like to print out "Hello world" for example (actual use would be more complicated):
public class Main {
public static void main(String[] args) {
Person person = new Person("John", "Doe");
person.getFirstName();
}
However I want to do this without modifying Person class (at least NOT before compilation). I read sth about Observable pattern and Property Change Listeners, but they don't seem to be doing what I'd want. Is such thing even possible in java ?
Related
This question already has answers here:
How can I get an Object's name in java?
(8 answers)
Closed 7 years ago.
when an object is created how can i get the name of that object ??
for example let's consider a class Book:
public class Book {
private String name;
private int pages;
public Book(String name, int pages) {
this.name = name;
this.pages = pages;
}
}
// now i create an object of this class
Book book = new Book("Java",100);
i want to get the name of the object created that is "book", is there any way to get it ?
i tried the toString(), function and it does not work it prints something like this: #3d4eac69
If you mean the name property, you can't with your code as written. You'd need to either make name public, or provide a public getter for it
If you mean the name of the class, it would be
book.getClass().getName()
If you mean the name of the variable you've assigned it to (book), you can't, that isn't information available at runtime (outside of a debug build and debugger introspection).
You have to create the getter method in Book class. Would be like:
public String getName() {
return this.name;
}
And then you would call:
book.getName();
Use:
book.getClass().getName();
Every object in Java has getClass() method:getClass() documentation
And every Class object has its name:
getName() documentation
This question already has answers here:
What is Double Brace initialization in Java?
(13 answers)
Closed 7 years ago.
I have a class User, only have two fields: id, name
package test;
public class User {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Then in the Main class, I tried to initialize the User object with two different approach:
package test;
/**
* #author lhuang
*/
public class Main {
public static void main(String[] args) {
User u = new User() {
{
setId(1l);
setName("LHuang");
}
};
System.out.println(u.getClass());
User u2 = new User();
u2.setId(1l);
u2.setName("LHuang");
System.out.println(u2.getClass());
}
}
then I can get the output
class test.Main$1
class test.User
The interesting is why the u class is the inner class type of Main? But actually I still can use the u.getId() and u.getName() method.
You're creating an anonymous class that extends from User here:
User u = new User() { //<-- this open bracket defines a new class
{
setId(1l);
setName("LHuang");
}
};
This
User u = new User() { // here's your derived class
{ // here's the initialiser block
setId(1l);
setName("LHuang");
}
};
creates a new anonymous subclass of User (the outer set of braces), and then defines an initialiser block within that (the inner set of braces).
It's often advised to avoid the above construction for reasons of clarity (not many people are aware of how it works), and since you're creating an inner class, it'll have an implicit reference to the outer class. This can cause issues for garbage collection and serialisation.
Having said that, I would use the above sparingly (e.g. for setting up test collections in unit tests etc. due to its conciseness)
This question already has answers here:
Getting enum associated with int value
(8 answers)
Closed 7 years ago.
i have a enum
public enum Category {
NonResidential("Non-Residential"), Residential("Residential");
private String category;
BuildingAssetCategory(String s) {
category = s;
}
public String getType() {
return category;
}
public void setType(String type) {
this.category = type;
}
}
I want to get the enum on the basis of value its having.
i have String of value Non-Residential, then how can i get the enum returning `NonResidential.
P.S i to want to create own magic rather then something java supports.
i have read out many question like this but i want different ans.
There is no magic here, since it's your own define field ('category') you should write your own static method to search by it. For example:
public enum Category {
...
public static Category findByName(String cat){
// loop over Category.values() and find the requested cat
}
btw ValueOf will work if you provide the enum name (e.g. "NonResidential") but it won't work for category name (e.g. "non-residential")
Use valueOf.
Category.valueOf("Non-Residential");
This will return you the enum.
This question already has answers here:
How to create a println/print method for a custom class
(6 answers)
Closed 8 years ago.
Hello I have question to my small program how I can print the value of p1? When I am using p1.toString() method this still shows me the address of an object I was searching in google some other ways and I still don't know how to do this. Here is the code:
public class Boss {
String name;
public Boss(String input) { // This is the constructor
name = "Our Boss is also known as : " + input;
}
public static void main(String args[]) {
Boss p1 = new Boss("Super-Man");
System.out.println(p1.toString());
}
You seem to have forgotten to override toString()
// Add this to Boss
public String toString() {
return name;
}
Or (as you currently have your code),
// System.out.println(p1.toString());
System.out.println(p1.name);
You should probably add a getName() method to Boss as well,
public String getName() {
return name;
}
You need to override the toString method to get the functionality that you are expecting. Also I recommend setting the String name to private while you're at it. If you need to provide access to the String then create a get method to return it. This prevents someone from modifying it when they shouldn't have access. Not providing an access modifier in Java defaults to protected.
public class Boss {
private String name; // Change access modifier to private
public Boss(String input) {
name = "Our Boss is also known as : " + input;
}
#Override
public String toString(){ // Override the toString method
return name;
}
public static void main(String args[]) {
Boss p1 = new Boss("Super-Man");
System.out.println(p1.toString());
}
}
The default toString() method in Object prints class name # hash code. You can override toString() method in your class to print proper output.
#Override
public String toString(){
return name;
}
Sources:
http://javarevisited.blogspot.com/2012/09/override-tostring-method-java-tips-example-code.html
http://www.geeksforgeeks.org/overriding-tostring-method-in-java/
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to java in general but I am having a lot of trouble with objects specifically. I have a project to pass an object to another object. I've looked all over the internet for help, my online java textbook doesn't explain objects in detail. So my question is, how would you pass an object to another object.
-Thank you in advance
Messaging between objects is a core concept in object-oriented programming. To "pass an object to another object" generally just means that one object exposes a method which accepts the type of another object as a parameter to that method. It could be something as simple as this:
class Person {
private String name;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}
class Car {
private Person driver;
public void setDriver(Person driver) {
this.driver = driver;
}
}
Then somewhere in the code, you'd have an instance of a Car and an instance of a Person, and you'd call that method:
carInstance.setDriver(personInstance);
Those instances could have been created lots of different ways. Perhaps even as simple as:
Person personInstance = new Person();
personInstance.setName("David");
Car carInstance = new Car();
You can pass an object o1 to another object o2 through calling a method of o2 (or a constructor of o2's class in particular; constructors as you know are special types of methods).
I suggest you start by figuring out what this code below does.
How many persons are there?
What are their names at different moments of the execution of the program?
How many times and where a Person object is passed to a Person object?
How many times and where a String object is passed to a Person object?
If you digest this, you'll be good for now.
class Person {
private String name;
public Person(String name){
this.name = name;
}
public Person(Person p){
this.name = p.name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class MainProg {
public static void main(String[] args) {
Person t1 = new Person("Joe");
Person t2 = new Person("John");
System.out.println(t1.getName());
System.out.println(t2.getName());
t1.setName("Mark");
System.out.println(t1.getName());
System.out.println(t2.getName());
Person t3 = new Person(t1);
System.out.println(t3.getName());
}
}