We know that when we pass any object like list, map or any object to System.out.println(), it will get the list.toString(), map.toString(), object.toString()as parameter automatically.
I want to create user defined function like this.
static void print(String s)
{
//someprocessing
}
But for this method when I pass any object to it should be converted explicitly to string.
for example,
print(list.toString());
But I want to define a method that will implicitly convert object to its toString. Can anyone tell me how to do that in java ?
I did something Like this to solve this !
static void print(Object o)
{
System.out.println(o.toString());
// String rep = o.toString();
}
So I can use it on any Object type except for primitives.
Related
Assume i want to have a method that get an object of any type in my application to validate all fields it has (each object has different fields with different types) and wrap it to a message. so the method input argument would be instance of any object
Now my question is :
what's the difference between having this input argument as an Object or Class<?> ?
as i know ? means 'any type or class' and 'Object' is a super type in java .
i appreciate if Someone could explain me in which cases better to use this :
public validateAndConvertAnyObject(Object obj) {
// compute and return a message
}
and when it's better to use this ?
public validateAndConvertAnyObject(Class<?> obj) {
// compute and return a message
}
First you don't specify a return type in your method.
It is not valid.
Second, these two parameters are totally different.
public validateAndConvertAnyObject(Object obj)
can accept any object.
While public validateAndConvertAnyObject(Class<?> obj)
can accept any class.
The equivalent of
public validateAndConvertAnyObject(Object obj)
with generic would be :
public <T> void validateAndConvertAnyObject(T obj){
After compilation and type erasure, these provide the same compiled class.
So in this example, using Object makes more sense as more explicit.
To convert an instance to another class with reflection, generally, you pass the target class :
public <T> T validateAndConvertAnyObject(Object obj, Class<T> targetClass){
...//processing on obj
}
And you could use it :
MyObject myObject = ...;
MyOtherClass myOtherClass = validateAndConvertAnyObject(myObject, MyOtherClass.class);
The first method can be called with any object as an argument, eg "foo", 42 or Integer.class. The second one will only accept class objects, eg "foo".getClass() or String.class
What is the difference between Class<?> and Object
Object
This takes the instance as a parameter
Class<?>
This takes a class as a parameter
Example
Object could be equal to String, and for a similar result you could have Class<?> equal to java.lang.String.
Confusion
Technically, you could pass an instance of Class<?> as an Object, which adds confusion, which is a good reason to use Class<?> instead, as it prevents mixing up the instance and it's class.
Object actually represents an instance of a created object like:
String text = "Hello World!";
Object textAsObj = (Object) text;
Whereas Class only represents the class of objects, it has no connection to an actual instance of this class:
Class<?> textClass = Class.forName("java.util.String");
So you should probably use the Object variant if you want to access specific values of an instance. You can, at anytime, retrieve the class from an Object using the getClass method:
String text = "Hello World!";
Class<String> textClass = text.getClass();
And here is an example how you could use that to access a field of a given Object:
Person person = new Person("John Doe");
Class<Person> personClass = person.getClass();
Field nameField = personClass.getDeclaredField("name");
String name = (String) nameField.get(person);
I am trying to call getter method on object but which getter to call depends on the value in a variable.
public void met1(String var) {
MyClass m = new MyClass();
if(var.equals("A"))
m.getA();
if(var.equals("B"))
m.getB();
if(var.equals("C"))
m.getC();
}
This is one way. Another could be using switch but I don't want to hardcode values as they may change. Is there any better way of doing this?
String is a class not a primitive type, you can't compare instances of String class like var using == this will not work!!!
You need to use method equals like: if(var.equals("A")) then ... .
Apart form that this way is fine.
Another way would be using reflection without if-statement:
Class<?> c = Class.forName("MyClass");
Object my_object = c.newInstance();
Method setNameMethod = my_object.getClass().getMethod("get"+var,String.class);
setNameMethod.invoke(my_object, var);
I've got some classes which include toString functions which work very well as:
snipped of declaration:
public String toString() {
return "Port info: "+myPort.variable;
}
snipped of main():
Port myPort;
myPort.fillInfo();
system.out.println(myPort);
output:
"Port info: 123"
I'm trying to replace all my system.out.println(myPort) calls with myWindow.println(myPort) calls where myWindow contains:
public void println(String toPrint)
{
textArea.append(toPrint+"\n"); //or insert
}
However, I'm getting:
The method println(String) in the type window is not applicable for the arguments (Port)
In other words, my declaration is expecting the String type, and I'm trying to pass it the Port type.
Somehow, system.out.println() will take any class that's got a toString() declared.
How does system.out.println take any class and print it out, and run its toString() method if it exists? And, more to the point, how can I replicate this functionality for my own println() function?
Change your Window to
public void println(Object obj)
{
textArea.append(obj +"\n");
}
PrintStream.println has an overload that takes an Object argument. You can make your println do the same.
First, please don't use \n as a line separator (it isn't portable). In addition to overloading println(Object), you could make your method generic. Something like
public <T> void println(T obj)
{
textArea.append(String.format("%s%n", obj));
}
or
public void println(Object obj)
{
textArea.append(String.format("%s%n", obj));
}
or
public void println(Object obj)
{
textArea.append((obj == null ? "null" : obj.toString())
+ System.lineSeparator());
}
The problem is that System.out has a method to print to console an object as it contains for all primitive data types. The thing about this is that as all methods have the same name and just change the data type of the parameter you want to print, you think you can pass an object by a string and is not. The method .println() automatically takes which passes an object. Within this method .println() he takes the object that you indicated by parameters and calls his method .toString() to obtain the string representation of the object and printed on the console.
If you want to print any type of object you must declare your parameter as object type and invoke the method .toString() from the object and print that information.
If I am printing an object of the class then it is printing the toString() method implementation even I am not writing the toString() method so what are the implementation,how it is calling toString() internally?
You're not explicitly calling toString(), but implicitly you are:
See:
System.out.println(foo); // foo is a non primitive variable
System is a class, with a static field out, of type PrintStream. So you're calling the println(Object) method of a PrintStream.
It is implemented like this:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
As we see, it's calling the String.valueOf(Object) method.
This is implemented as follows:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
And here you see, that toString() is called.
Every object in Java IS-A(n) Object as well. Hence, if a toString() implementation has not been provided by a class the default Object.toString() gets invoked automatically.
Object.toString()'s default implementation simply prints the object's class name followed by the object's hash code which isn't very helpful. So, one should usually override toString() to provide a more meaningful String representation of an object's runtime state.
even I am not writing the toString() method so what are the implementation,how it is calling toString() internally?
toString() is one of the few methods (like equals(), hashCode() etc.) that gets called implicitly under certain programmatic situations like (just naming a few)
printing an object using println()
printing a Collection of objects (toString() is invoked on all the elements)
concatenation with a String (like strObj = "My obj as string is " + myObj;)
Everything inherits from Object, so the toString on Object will be called if you have not defined one.
toString() method is present in Object class, so when u put obj in System.out.println(obj);, impliciyly it will call toString() present in Object class since every user created class will implicitly inherits Object class so as ur newly created class, that means that toString() is available in ur class so it will print something like for example: "PkgNamePackage.Classname#12cf4"
However if u explicitely override toString method and give ur own implementation then it will written the string what ever u give in Overriden tostring method();
ex:
public class DogArray {
#Override
public String toString() {
return "Im the newly created Object";
}
public static void main(String args[]) {
DogArray d1 = new DogArray();
System.out.println(d1);
}
}
output: Im the newly created Object
In java object class is super class to the each and every class.whenever your passing parameter to the system.out.println internally object class to string method will be excuted.it returns class name#reference value given but as per our application requirement object class to string method will override in collection and string class.it returns their content.
I'm trying to figure out how java classes work.
When I create a StringBuilder:
StringBuilder testString = new StringBuilder("Hello World!);
If I want to, say, get the value that testSting holds a reference to, I can simply call it like: System.out.println(testString);
This is cool behavior, but I'm unsure how to replicate it in classes that I make.
For instance, if I were to try and re-implement my own version of StringBuilder, the approach I would take (as a beginner), would be this:
class MyBuilder {
char[] string;
public MyBuilder(String s) {
string = new char[s.length()];
string = s.toCharArray();
}
So, to make the string an array I had to store it in a data field of the class. But then, to access this in my code, I can't print it by simply calling the variable name. I would have to use .property syntax. Thus, to duplicate the above example, I would have to type System.out.println(testString.value); Which isn't nearly as pretty.
How do you make a class such that it behaves like String or StringBuilder and returns its value without manually accessing the data fields?
Implement a toString method.
toString is a method on Object, so every java object inherits one. The default implementation that you inherit is only useful for getting the class type, and for distinguishing one object from another; the format is: ClassName#HashCode. There are no details unique to your implementation.
In your own classes, to get the description that you want you'll need to override the toString method, so that in contexts where a String is expected, e.g. when you call System.out.println(myObject.toString());, your own format is used.
It's often a good idea to do this, for a more readable description of your object. You can always call super.toString to include the output from the default - ClassName#HashCode - in your own output.
You can override Object.toString() in your object MyBuilder. System.out.println calls on this method for every object used. For example here, you could use:
#Override
public String toString() {
return Arrays.toString(string);
}
Overwrite the toString-Method
private String value;
public MyClass(String value) {
this.value = value;
}
public String toString() {
return value;
}