Using instanceof with a class Object [duplicate] - java

This question already has answers here:
Is there something like instanceOf(Class<?> c) in Java?
(8 answers)
Closed 7 years ago.
What's the correct syntax to make this work?
public boolean isTypeOf(Class type) {
return this instanceof type;
}
I intend to call it with:
foo.isTypeOf(MyClass.class);
The method will be overriden, otherwise I would just use instanceof inplace.

Use Class.isInstance(obj):
public boolean isTypeOf(Class type) {
return type.isInstance(this);
}
This method determines if the given parameter is an instance of the class. This method will also work if the object is a sub-class of the class.
Quoting from the Javadoc:
This method is the dynamic equivalent of the Java language instanceof operator.

Related

Primitive and Wrapper return types java [duplicate]

This question already has answers here:
Why doesn't my primitive-type-argumented method override the wrapper-type-argumented super class method?
(3 answers)
Closed 4 years ago.
Why does not Java allow to override method as follows?
class Test1{
Integer test(){
return 5;
}
}
class Test2 extends Test1{
int test(){
return 4;
}
}
It produces int not compatible with integer error?
You should really try googling overriding methods return type here
Yes it may differ but their are some limitations. Before Java 5.0, when you override a method, both parameters and return type must match exactly. In Java 5.0, it introduces a new facility called covariant return type. You can override a method with the same signature but returns a subclass of the object returned.
so int is primitive and Integer is wrapper class, no relation between them

Java - Pass class as argument and use it to call a function [duplicate]

This question already has answers here:
Passing a class ("Country.class") as an argument in Java
(7 answers)
Closed 7 years ago.
is there a way of getting a class as argument and then from that class variable call a function?
(I don't know the class name, but i know the function name)
public void executeFunction(RandomClass class1){
class1.sayHi();
}
You can use reflection to do this. Example:
public void executeFunction(Class class1) throws Exception{
for(Method m : class1.getMethods()){
if(m.getName().equals("sayHi"))
m.invoke(class1.getConstructor().newInstance());
//default constructor used to get a object of the class
//if there is not default constructor this will fail
}
}

java - Generic Return Type? [duplicate]

This question already has answers here:
Create instance of generic type in Java?
(29 answers)
Closed 8 years ago.
I'm not certain if this is possible in Java. Also, I'm not able to figure out what to query on Google for this.
Anyway, I want a method that takes as an argument a Class (interface or class) and the method's return type is an instance of that Class. I don't want to have to recast an Object after the fact.
I'm not certain if this feature exists or what the syntax would be. Let's say I have a class named XYZ and here is my pseudo method.
private XYZ createInstance(XYZ.class, other args) {
...
// create an instance of XYZ with other args named "_xyz_"
...
return _xyz_;
}
Now assume XYZ is some sort of generic syntax. Is this possible at all in Java? Thanks for any help.
private <T> T createInstance(Class<? extends T> c) {
return c.newInstance();
}
Use the diamond operator:
private <T> T createInstance(Class<T> concreteClass){
return concreteClass.newInstance();
}
//usage
Integer i = instanceWithThatMethod.createInstance(Integer.class);
To pass "arguments", you have to get the Constructor of the class matching the desired parameter types, and invoke the call on that one, like this:
private <T> T createInstance(Class<T> concreteClass, String stringArg){
return concreteClass.getConstructor(String.class).newInstance(stringArg);
}
//usage
SomeClass s = createInstance(SomeClass, "testString");
//equals
SomeClass s = new SomeClass("testString");
//where SomeClass HAS to serve:
public SomeClass(String s){
...
}

What is the output for the following Java program where null is passed as argument for the overloaded methods? [duplicate]

This question already has answers here:
Java method dispatch with null argument
(4 answers)
Closed 9 years ago.
public class Overloading {
public static void main(String[] args) {
Overloading o = new Overloading();
o.display(null);
}
void display(String s) {
System.out.println("String method called");
}
void display(Object obj) {
System.out.println("Object method called");
}
}
It is giving the output as "String method called". I need the explanation why?
Taken from the Java Spec:
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
First of all: both methods are accessible (obviously) and applicable. They are both applicable, because null is of type nulltype, which is by definition a subtype of all types. String is more specific than Object, because String extends Object. If you would add the following, you will have a problem, because both Integer and String are equally "specific":
void display(Integer s) {
System.out.println("Integer method called");
}
Java will always find the most specific version of method that is available.
String extends Object, and therefore it is more specific.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5

What is the equivalent to "ByRef" in Java? [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 9 years ago.
I'm working on translating some code from VisualBasic to Java and I've encountered a snag when using the ByRef keyword in VB. That doesn't exist in Java!
How should I simulate a ByRef call in Java?
Edit: Just to clarify for those who don't know VB, ByRef identifies a variable in the parenthesis after calling a function and makes it so that when that variable is changes inside of the function, it will also change higher up where it is called as opposed to ByVal where only the value of the variable is remembered. Changing a ByVal variable in the method will not affect the variable where it is called.
You can't. Everything in Java is passed by value, including object references. However you could create a "holder" object, and modify its value inside a method.
public class Holder<T> {
T value;
public Holder(T value) {
this.value = value;
}
// getter/setter
}
public void method(Holder<Foo> foo) {
foo.setValue(something);
}
Java does not have an equivialent.
You either need to return the object from your method, and assign it back, e.g.
myInteger = doSomething(myInteger);
Or you need to make a wrapper object, these are often name a Holder.
If you have a variable named myInteger that you want some method to change, you
pass it to that method as a member of the "Holder" class.
e.g. (This can naturally be made into a generic)
class IntegerHolder {
public Integer myInteger;
}
IntegerHolder myHolder;
myHolder.myInteger = myInteger;
doSomething(myHolder);
//use the possibly altered myHolder.myInteger now.
Inside doSomething, you can now change myHolder.myInteger , and the method calling
doSomething() can see that change, e.g.
void doSomething(IntegerHolder holder)
{
holder.myInteger = holder.myInteger * 100;
}

Categories

Resources