I have quite a few getter methods in a class and I need to print the return of those getters (Just one and not all of them at once). I need to be able to do this with one print() method but I am not sure how to do this. Is there a way to dynamically call another method and then print the return of that method?
Here are a couple of getter methods:
public String getEmail()
{
return this.studentEmail;
}
public Integer getAge()
{
return this.studentAge;
}
Here is what I am wanting to do:
public void print(???)
{
System.out.println(theGetterMethod);
}
I know that I can create a bunch of print methods but I need to be able to do this with one method.
As asked by the OP:
"I think you were correct with your first comment and it can be an answer."
From:
"You can tackle it by using Sytem.out.println ("E-mail: " + ...getEmail(), " Age: " + ...getAge()); If you want to go overkill you can use reflection."
Meaning instead of having a seperate print() method you will instead be invoking the right accessor for the value you want to print.
This is one of reasons why you use accessors in the place, as now you are exposing the fields without any risk of having the user change them.
You can still change on underlying Objects apart from String as it is immutable.
You can call methods dynamically based on their name by using reflection.
In this example I assume that each Getter follows a pattern and just pass over the property name that I want to print out:
import java.lang.reflect.Method;
public class Student {
private String studentEmail = "MyEmail";
private Integer studentAge = 20;
public String getEmail() {
return this.studentEmail;
}
public Integer getAge() {
return this.studentAge;
}
// Prints out a property based on the name
public void print(String property) throws Exception {
for (Method method : this.getClass().getMethods())
if (method.getName().equals("get" + property))
System.out.println(method.invoke(this, null));
}
// Prints out all properties with a getter
public void print() throws Exception {
for (Method method : this.getClass().getMethods())
if (method.getName().startsWith("get"))
System.out.println(method.invoke(this, null));
}
}
And than call the method like that:
Student s = new Student();
s.print("Email");
s.print("Age");
Related
I am reading a code which is done something like this, and I want to understand why it is doing this:
public abstract class Class2 extends Class1 {
...
#Override
public ObjectType someFunction() {
ObjectType var = super.someFunction();
....
return var;
}
}
So the someFunction() method has been overwritten and the someFunction() of the parent is called again inside it.
Does it make sense to you? What would be the motivation for doing this?
If you don't want to duplicate the code for the entire overridden method, but you want to change the logic a little bit or if you want to add a little bit of code, then you can call the overridden method and provide additional code.
This prevents duplication of code and logic in subclasses that wish to override a method but retain some behavior.
As yshavit has indicated in a comment, calling the overridden method may be the only way to access data that is private in the superclass.
Pretty usefull when you want to use inheritance properly.
Just imagine that you have a class Person which is composed by a name and a surname and you want to specify the job, like Farmer.
class Person {
private String name;
private String surname;
//... Constructor
public String getInfos() {
return this.name + " " + this.surname;
}
}
class Farmer extends Person {
//... Constructor
#Override
public String getInfos() {
return super.getInfos() + " is a farmer.";
}
}
Person p1 = new Person("Name", "Surname");
System.out.println(p1.getInfos());
// Show "name surname"
Person p2 = new Farmer("Name", "Surname");
System.out.println(p2.getInfos());
// Show "name surname is a farmer."
I am trying to build a class with a constructor, mutators and accessors. Reading through books and online, I am made to learn that you can call a constructor with or without parameters. However, my case below seems not to work. I am not even able to compile without errors. It works when I use student jane = new student(""). What am I doing wrong?
Devolution.java:6: cannot find symbol
symbol : constructor student()
location: class Governor
student jane = new student();
^
public class designers {
public static void main(String[] args) {
student jane = new student();
student smith = new student("jane", "36365355", "Nairobi", "Male");
System.out.println("Janes's Properties: "+jane.name() + " " + jane.nationalID() + " " + jane.county()+" "+jane.gender());
System.out.println("Smith's Properties: "+smith.name() + " " + smith.nationalID() + " " + smith.county()+" "+smith.gender());
}
}
other code is below
public class student {
//Private fields
private String name;
private String nationalID;
private String county;
private String gender;
//Constructor method
public student(String name, String nationalID, String county, String gender)
{
this.name = name;
this.nationalID = nationalID;
this.county = county;
this.gender = gender;
}
//Accessor for name
public String name()
{
return name;
}
//Accessor for nationalID
public String nationalID()
{
return nationalID;
}
//Accessor for county
public String county()
{
return county;
}
//Accessor for gender
public String gender()
{
return gender;
}
}
A constructor is a way of creating an instance of a class:
Student s = new Student(...);
will create a new instance of the Student class and enable you to access it using s.
Often, when you create an instance of a class, you need to specify certain information that's used in building the instance. In the case of a student, that might be the name, the age, and so on. You'd have a constructor that looks like this:
public Student(String name, int age) {
//...
}
But in some contexts, you can build an instance of a class without needing (at least initially) to specify anything. So you might, for instance, have a constructor like this
public Student() {
//...
}
which leaves the name and age fields blank or zeroed out, until you later set them with another method of the class.
The critical point for what you're doing is that you've made a constructor that requires various parameters, but you haven't specified one like this second example that doesn't require any. As things stand, you can write
Student s = new Student("Bob", "ABC12345", "Surrey", "Male");
because you've got a constructor that takes four Strings as arguments. But you can't write
Student s = new Student();
because you didn't create a constructor that takes no arguments.
The slight wrinkle in this is that if you don't specify any constructors in your class, then Java will automatically create one for you that takes no arguments and doesn't do anything special. So if you don't write any constructors, you'll get one for free that looks like this:
public Student() {
}
But that's only if you don't write any of your own. Since you've specified one that does take parameters, Java won't give you a no-argument one for free. You have to put it in yourself if you want to be able to create instances without any arguments.
You've only written one constructor - the one with four parameters. You don't have a constructor without parameters, so you can't write new student().
Note that if you don't write any constructors at all, the compiler will automatically make a constructor for you, without parameters, but as soon as you write one constructor, this doesn't happen.
By the way, most people use capital letters for class names (so Student, not student). This makes it easy to distinguish them from the names of other identifiers. It would be good for you to get into the habit of doing the same.
You don't have a constuctor without parameters in the student class. Such a constructor is generated by the compiler only if you haven't defined any other constructors, which you have.
Just add the constructor :
public student()
{
this.name = null;
this.nationalID = null;
this.county = null;
this.gender = null;
}
You need to make another constructor as follow:
public Student(){
//do things here
}
Explanation:
When no constructors are defined in a class then there is a default constructor(without
any parameters) already. In which case you don't need to define it. But if you have any constructor with some parameters, then you need to define the constructor without parameters as well.
Its called overloading the constructor. In your class, declare a constructor again without parameter requirements. See this post for more info
You don't have a constructor without parameters. That would only be the case when you had not write an own one. When you want to have the possibility to make an object of the class with or without parameters, you need two different constructors in your code.
I have an enum FooBar at class Clazz with falues FOO and BAR like this:
class Clazz {
enum FooBar{
FOO,
BAR
}
}
I now would like to use wicket getString() method to localize the values FOO and BAR. The best I can do is to define at i18n file
Clazz.FooBar.FOO=foo
Clazz.FooBar.BAR=bar
and I get values with this code
fooBar = FooBar.FOO;
getString("Clazz.FooBar." + fooBar.name());
I have heard that this could be achieved without Clazz.FooBar addition to the i18n query string, but the method to be called would be different. How to do this?
You can put this method in your base page/panel:
public String getString(Enum<?> value) {
Class<?> enclosingClass = value.getClass().getEnclosingClass();
String key = (enclosingClass == null ? "" : enclosingClass.getSimpleName() + ".")
+ value.getClass().getSimpleName() + "." + value.name();
return getString(key);
}
Then you can simply call it with
getString(Clazz.FooBar.FOO);
and it will return what you defined in the property file.
I will not advice you to directly store enum constant names in properties file the reason is simple two different enums can hold same name.
Below is the code I have come up with
class Clazz {
enum FooBar {
//StrId are keys from property file e.g. below
FOO("com.abc.classz.foobar.FOO"), BAR("com.abc.classz.foobar.BAR");
private final String strId;
private FooBar(String id) {
this.strId = id;
}
// toString can also be used here I am just keen on having seperate
// method
public String getName() {
//Load Value for strId from properties file
return null;
}
}
}
This will keep your enum and your i18n purpose separate and clear.
See below sample Enum class. You may want to customize it more depending on your needs.
public enum FooBar {
foo("foobar.foo"),
bar("foobar.bar");
private String key;
ErrorCodeEnum(final String key) {
this.key = key;
}
public String toString() {
return key;
}
}
then you can make the toString method to return key directly so you can use
getString(ErrorCodeEnum.ERROR1);
or you can override the toString method directly like below
public enum FooBar {
foo, bar;
public String toString(){
return getClass().getName()+"."+name();
}
}
You could simply define
FOO=foo
BAR=bar
in your properties and access it by
getString(fooBar.name());
or am I missing some point?
I was looking for something called EnumChoiceRenderer. The main idea is to give a EnumChoiceRenderer for e.g. DropDownChoise element and you're able to give parameters of the kind I was proposing in my question. Ok, in this solution you're able to give only
FooBar.BAR=bar
FooBar.FOO=foo
in your resource file but this is the closest I could find when I investigated this more with my spare time.
PS. Click the EnumChoiseRenderer in the beginning of this answer to see the article of this solution.
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I am a newbie in java. Say, I have a class Individual. I want to print
Individual ind = new Individual();
System.out.println(ind);
Above code gives output like this:
Individual#1922221
What is the significance of this?
Is it some kind of unique id
for that object?
Can I customize this? I mean write a function of
my own which will give output when I print?
If so, how can I do
this?
If you want to print meaningful content of any object, you have to implement your own toString() method, which will override the parent(Object) class's toString() method. By default all the classes(Whatever you create) extends Object class.
Sample Code:
public class Individual {
private String name;
private String city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Name of Individual :").append(this.getName())
.append("\nCity :").append(this.getCity());
return builder.toString();
}
public static void main(String[] args) {
Individual individual = new Individual();
individual.setName("Crucified Soul");
individual.setCity("City of Crucified Soul");
System.out.println(individual);
}
}
Output:
Name of Individual :Crucified Soul
City :City of Crucified Soul
If you have bigger class with many variables, you can use XStream to implement your toString() method. XStream will print your object meaningful in XML format. Even you can parse them back to equivalent object. Hope this would help you.
This is the result of default toString() method - the classname + hashcode. This can be override by overriding toString().
Some reference here: http://www.javapractices.com/topic/TopicAction.do?Id=55
Since it hasn't been explained yet, overriding the toString() method simply means that you create a toString() method of your own in your class. By putting your own version of toString() in your class, you make it so that java will use your toString() method rather than the default. Because the original toString() method returns a string, however, your toString() method must also return a string. Your Individual class would look something like this:
public class Individual{
//any other code in the class
public String toString(){
return "your string";
}
}
Then, when you called your System.out.print(ind); it would print out your string.
I think you want to overwrite Individual toString. See http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#toString()
I am trying to understand the principle of information hiding. Suppose that I have a vehicle class with methods such as getSpeed, setSpeed, getEngine, setEngine, getVIN, setVIN, etc. To enforce info hiding, I wouldn't want to give client classes the ability to setVIN since a vehicle only has one VIN (I might be wrong). I am kind of confused on how to make this class apply info hiding. I wouldn't want to make setVIN to private. But how do you set the VIN once and not allow it to be set again afterwards? Or should I even do it that way?
Information hiding means you're not exposing the internal VIN field for direct modification from the outside. Having a setter does not violate the hiding principle, because you have the control over the fields modification.
In your case, if you want to make sure the VIN is only set once, best way to do it is by setting it in the constructor, and removing the setVIN.
BTW, although this is a general question (which is fine), if you have a specific language in mind, it might be worth mentioning. Some languages do not allow non-default constructors, for instance. In that kind of language, I'd leave the setVIN, but have it check whether the VIN has already been set when called. If it had, either ignore the call, or throw an exception.
Just because a class / object has a property, conceptually speaking, it doesn't mean it should be public. A "property" can be assigned & changed with "getter" & "setter" functions, but you may only expose as public the ones you need.
You may say, "Show me the code":
public class JavaClass {
// hidden field "name"
protected String name;
// start property "Name"
// note: uses "name" field to store the property
public void setName(String value) {
//set passed parameter as name
name = value;
}
public String getName() {
return name;
}
// finish property "Name"
// start property "Id"
// note: uses "name" field to store the property
public void setId(String value) {
//set passed parameter as name
name = value;
}
public String getId() {
return name;
}
// finish property "Id"
// hidden field "years"
protected int years
// functions works as "read-only" properties
public int Years() {
return years;
}
// start constructor
public JavaClass() {
name = "unknown";
years = 1;
}
// finish constructor
public static void main(String args[]) {
JavaClass javaObject = new JavaClass();
//set name member of this object
javaObject.setName("Visitor");
// print the name
System.out.println("Hello: " + javaClassExample.getName());
//set name member of this object
javaObject.setId("Employee");
// print the name, not the Id, but are the same
System.out.println("Hello: " + javaClassExample.getName());
// and current years of age
System.out.println("Years: " + javaClassExample.Years());
} // public static void
} // class JavaClass
Its not tested, but, I think, it explains my point.