How to get elements from Generic Object? - java

public void method(Object variable){
System.out.println(variable.toString());
}
When I invoke the method above, I get the following output:
<Heading element1=value1 element2=value2 element3=value3/>
How can I get only 'value3' from this object's toString method without resorting to String operations or Regex with the Matcher class?

As it has been remarked in the comments, you cannot do what you're attempting without using a regex or at least casting the Object to something more specific and then retrieving the property value you're looking for.
You might want to try something like
public void method(Object variable){
if (variable instanceof MyClass){
MyClass mc = (MyClass) variable;
System.out.println(mc.getMyProperty());
} else {
//... regex implementation ...
}
}

Related

How can I return objects of different type from a single function?

I need to return objects of different classes in a single method using the keyword Object as the return type
public class ObjectFactory {
public static Object assignObject(String type) {
if(type.equalsIgnoreCase("abc")){
return new abcClass();
} else if(type.equalsIgnoreCase("def")) {
return new defClass();
} else if(type.equalsIgnoreCase("ghi")) {
return new ghiClass();
}
return null;
}
}
and in another class I am trying to get the objects as
public class xyz{
public void get(){
Object obj=(abcClass)ObjectFactory.assignObject("abc");
}
}
How can I access the methods in abcClass using the obj object??
Your current code will throw an exception if assignObject returns an instance that is not an abcClass, so you can change the type of obj to absClass :
public void get(){
abcClass obj=(abcClass)ObjectFactory.assignObject("abc");
}
I would suggest as one of the commentators on your initial post did. That is, refactor this to use an interface.
Your classes AbcClass, DefClass, and GhiClass, could all implement an interface, lets call it Letters. You can then define a class called LettersFactory, with the method createLetters. At this point, I'd also recommend changing your hard coded string identifiers into an enumeration. For instance:
public enum LetterTypes { ABC, DEF, GHI }
You're factory method can then accept this enumeration, and you have no fears of getting invalid values. The factory method can also return the type Letters (the interface) and you have a more specific version of Object (which is good).
Finally, if you need to determine these types on the fly, you can have a method defined in Letters (forcing all children to implement it) called getType() which returns the LetterTypes enumeration for the class that is implemented.
You could also use the instanceof operator to determine which class you have.
Cheers,
Frank
You can use this as a refrence :-
public Object varyingReturnType(String testString ){
if(testString == null)
return 1;
else return testString ;
}
Object o1 = varyingReturnType("Lets Check String");
if( o1 instanceof String) //return true
String now = (String) o1;
Object o2 = varyingReturnType(null);
if( o2 instanceof Integer) //return true
int i = (Integer)o2;
So similarly you can use your own conditions along with the instanceof operator and can cast it to get the actual object type from Object type.

Print the type name of object held by variable

In Java, is it possible to print the type of value held by variable?
public static void printVariableType(Object theVariable){
//for example, if passed argument is "abc", print "String" to the console.
}
One approach to this problem would be to use an if-statement for each variable type, but that would seem redundant, so I'm wondering if there's a better way to do this:
if(theVariable instanceof String){
System.out.println("String");
}
if(theVariable instanceof Integer){
System.out.println("Integer");
}
// this seems redundant and verbose. Is there a more efficient solution (e. g., using reflection?).
I am assuming that in case of Animal myPet = new Cat(); you want to get Cat not Animal nor myPet.
To get only name without package part use
String name = theVariable.getClass().getSimpleName(); //to get Cat
otherwise
String name = theVariable.getClass().getName(); //to get full.package.name.of.Cat
System.out.println(theVariable.getClass());
Read the javadoc.
You can use the ".getClass()" method.
System.out.println(variable.getClass());
variable.getClass().getName();
Object#getClass()
Returns the runtime class of this Object. The returned Class object is
the object that is locked by static synchronized methods of the
represented class.
public static void printVariableType(Object theVariable){
System.out.println(theVariable.getClass())
}
You can read in the class, and then get it's name.
Class objClass = obj.getClass();
System.out.println("Type: " + objClass.getName());
public static void printVariableType(Object theVariable){
System.out.println(theVariable);
System.out.println(theVariable.getClass());
System.out.println(theVariable.getClass().getName());}
ex- printVariableType("Stackoverflow");
o/p: class java.lang.String // var.getClass()
java.lang.String // var.getClass().getName()

Call a function from a string array (Java or Groovy)

In Java, or Groovy, say I have a String array like
myArray = ["SA1", "SA2", "SA3", "SA4"]
I want to call a different function based off of each string.
class Myclass{
public static void SA1() {
//doMyStuff
}
public static void SA2() {
//doMyStuff
}
...etc
}
I would love to be able to loop through my array and call the functions that they pertain to without having to compare the string or make a case statement. For example is there a way to do something like the following, I know it doesn't currently work:
Myclass[myArray[0]]();
Or if you have suggestions of another way I can structure something similar.
In groovy you can do:
Myclass.(myArray[0])()
In Java you can do:
MyClass.class.getMethod(myArray[0]).invoke(null);
In Groovy, you can use a GString for dynamic method invocation:
myArray.each {
println Myclass."$it"()
}
You can, for instance, declare an interface such as:
public interface Processor
{
void process(String arg);
}
then implement this interface, for example in singletons.
Then create a Map<String, Processor> where keys are your strings, values are implementations and, when invoking:
Processor p = theMap.containsKey(theString)
? theMap.get(theString)
: defaultProcessor;
p.process(theString);
I suggest you look at Reflection APIs, to call methods at runtime
check Reflection docs
Class cl = Class.forName("/* your class */");
Object obj = cl.newInstance();
//call each method from the loop
Method method = cl.getDeclaredMethod("/* methodName */", params);
method.invoke(obj, null);

How to check type of param class?

I have the following method:
public static String getServiceUri(Class<?> c) {
// I'd like to check which type the parameter is...
if(c.getClass().equals(MyClass.class)){
do stuff 1
} else {
do stuff 2
}
}
Invoke method:
getServiceUri(MyClass.class);
On getServiceUri I want to call a WebService based on the type of a ServiceClass.
I know that equals will compare objects instance, but in this case I'm trying to discover the type of object.
Anyone know how I can compare using this kind of approach?
instanceof operator is the best choice..
you can do something like this
if(c instanceof MyClass){
//do your stuff
}
public static String getServiceUri(Class<?> classParam) {
if(classParam instanceof MyClass){
}
}
This is WRONG. It does not even compile because classParam needs to be an actual instance(object) to use the instanceof operator: hence the name.
If you want to know if the classParam is exactly equal to MyClass.class:
public static String getServiceUri(Class<?> c) {
if(classParam == MyClass.class){
}
}
However, if you want to check the entire hierarchy of classParam against MyClass then you can do classParam.isAssignableFrom(MyClass.class)

Explicit vs implicit call of toString

I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception.
For instance:
System.out.println("obj: "+obj);
instead of:
System.out.println("obj: "+obj.toString());
Is there any difference apart from the null case?
Can the latter case work, when the former does not?
Edit:
What exactly is done, in case of the implicit call?
There's little difference. Use the one that's shorter and works more often.
If you actually want to get the string value of an object for other reasons, and want it to be null friendly, do this:
String s = String.valueOf(obj);
Edit: The question was extended, so I'll extend my answer.
In both cases, they compile to something like the following:
System.out.println(new StringBuilder().append("obj: ").append(obj).toString());
When your toString() is implicit, you'll see that in the second append.
If you look at the source code to java, you'll see that StringBuilder.append(Object) looks like this:
public StringBuilder append(Object obj) {
return append(String.valueOf(obj));
}
where String.valueOf looks like this:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Now, if you toString() yourself, you bypass a null check and a stack frame and go straight to this in StringBuilder:
public StringBuilder append(String str) {
super.append(str);
return this;
}
So...very similar things happens in both cases. One just does a little more work.
As others have said - use the "" + obj method.
According to The Java Language Spec:
If the term is null, use "null"
Primitive types are converted using the boxed-type constructor new Boolean(X) or whatever
toString() is invoked (or equivalent)
if the result of toString() is null, use "null"
Concatenate the strings.
No difference except, like you say, the null safety. Always prefer the former to the latter.
Actually, if your invariant says the object should never be null, it doesn't matter. So it depends on whether or not you accept obj to be null.
It is quite easy to write a generic reference type.
class ref
{
static public class Reference<T>
{
private T value;
public Reference(T value) { set(value); }
public Reference() { set(null); }
public void set (T value) { this.value = value; }
public T get () { return this.value; }
public String toString() { return String.valueOf(this.value); }
}
static void fillString (Reference<String> str)
{
str.set("foo");
}
public static void main (String[] args)
{
Reference<String> str = new Reference<String>("");
fillString(str);
System.out.println (str);
}
}
Running it gives the required output:
javac ref.java && java ref
foo

Categories