Check if java class is subclass

Java – Check if a Class Object is subclass of another Class Object in Java

I’m playing around with Java’s reflection API and trying to handle some fields. Now I’m stuck with identifying the type of my fields. Strings are easy, just do myField.getType().equals(String.class) . The same applies for other non-derived classes. But how do I check derived classes? E.g. LinkedList as subclass of List . I can’t find any isSubclassOf(. ) or extends(. ) method. Do I need to walk through all getSuperClass() and find my supeclass by my own?

Best Solution

boolean isList = List.class.isAssignableFrom(myClass); 

where in general, List (above) should be replaced with superclass and myClass should be replaced with subclass

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false . If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false .

a) Check if an Object is an instance of a Class or Interface (including subclasses) you know at compile time:

boolean isInstance = someObject instanceof SomeTypeOrInterface; 
assertTrue(Arrays.asList("a", "b", "c") instanceof List); 

b) Check if an Object is an instance of a Class or Interface (including subclasses) you only know at runtime:

Class typeOrInterface = // acquire class somehow boolean isInstance = typeOrInterface.isInstance(someObject); 
public boolean checkForType(Object candidate, Class type)
Java – What are the differences between a HashMap and a Hashtable in Java

There are several differences between HashMap and Hashtable in Java:

  1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
  2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
  3. One of HashMap’s subclasses is LinkedHashMap , so in the event that you’d want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap . This wouldn’t be as easy if you were using Hashtable .

Since synchronization is not an issue for you, I’d recommend HashMap . If synchronization becomes an issue, you may also look at ConcurrentHashMap .

Java – Is Java “pass-by-reference” or “pass-by-value”

Java is always pass-by-value. Unfortunately, when we deal with objects we are really dealing with object-handles called references which are passed-by-value as well. This terminology and semantics easily confuse many beginners.

public static void main(String[] args) < Dog aDog = new Dog("Max"); Dog oldDog = aDog; // we pass the object to foo foo(aDog); // aDog variable is still pointing to the "Max" dog when foo(. ) returns aDog.getName().equals("Max"); // true aDog.getName().equals("Fifi"); // false aDog == oldDog; // true >public static void foo(Dog d) < d.getName().equals("Max"); // true // change d inside of foo() to point to a new Dog instance "Fifi" d = new Dog("Fifi"); d.getName().equals("Fifi"); // true >

In the example above aDog.getName() will still return «Max» . The value aDog within main is not changed in the function foo with the Dog «Fifi» as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return «Fifi» after the call to foo .

public static void main(String[] args) < Dog aDog = new Dog("Max"); Dog oldDog = aDog; foo(aDog); // when foo(. ) returns, the name of the dog has been changed to "Fifi" aDog.getName().equals("Fifi"); // true // but it is still the same dog: aDog == oldDog; // true >public static void foo(Dog d) < d.getName().equals("Max"); // true // this changes the name of d to be "Fifi" d.setName("Fifi"); >

In the above example, Fifi is the dog’s name after call to foo(aDog) because the object’s name was set inside of foo(. ) . Any operations that foo performs on d are such that, for all practical purposes, they are performed on aDog , but it is not possible to change the value of the variable aDog itself.

Читайте также:  Jar to java decompiler online

For more information on pass by reference and pass by value, consult the following SO answer: https://stackoverflow.com/a/430958/6005228. This explains more thoroughly the semantics and history behind the two and also explains why Java and many other modern languages appear to do both in certain cases.

Related Question

Источник

Java check if class is subclass

calling instance methods on a partially initialized object is already a huge trouble, calling them even before superclass constructors would be a nightmare. If you manipulate classes : If you manipulate instances : Solution 2: You can check in the parent class if the variable implements your -interface, because the -variable references to the actual subclass object: So above code block will be executed for the subclass but not for Solution 3: You can just have a method like this in : Whether or not that’s a good idea depends on what exactly you want to achieve with this.

Java: how to tell if an object is of a specific subclass

Java: how to tell if an object is of a specific subclass.

I want to have a check to see if an object is of a particular subclass and have the check NOT come back true for other classes that have inherited from the same superclass.

subclass: apple and banana extend fruit

Then I have a check (if appleObject.isThisClass(apple))

So far all I’ve been able to find are ways to check that will still return true because they share the same superclass.

Hopefully that makes sense.

Assuming you have an object reference apple of type Banana or Apple; then something like this,

if (apple instanceof Apple) // true 

tells you if apple is of type Apple . Where as

if (apple instanceof Banana) // false 

Would exclude Banana and finally

if (apple instanceof Fruit) // true 

would include Banana or Apple ; but you should probably not be testing this in callers (tight coupling) — instead, you should try and encapsulate behavior in the Fruit «interface».

Given your additional question in the comment,

Fruit aFruit = aMethod(); // get a fruit. if (aFruit instanceof Apple) < Apple apple = (Apple) aFruit; // do apple things with the apple. apple.somethingOnlyApplesDo(); >// else if (aFruit instanceof Banana) < // Do Nothing With Bananas. // Banana banana = (Banana) aFruit; // >

Use the getClass() method that is inherited from Object.

Читайте также:  Vs code html autocomplete

Java — Check if an object is an instance of a class (but, Whether or not the instance is a subclass should be irrelevant in a normal program. Share. Follow answered May 22, 2013 at 9:53. Duncan Jones Duncan Jones. 64.2k 26 26 gold badges 184 184 silver badges 243 243 bronze badges. 8. 31. I think a lot of stack exchange questions are about situations that are out of the normal. – …

Java inheritance: How can you find which subclass an object belongs to?

I wasn’t quite sure how to word it in the title, but here is the use case.

I have a class Test. Test has an attribute called Letter as so

Letter can be one of several subclasses.

Now suppose that in a class (let’s call it driver), I have an instance of Test. I want to figure out whether this Test’s letter is A, B, C, etc. so that I can access attribute unique to the child class. See:

If I use t.getClass(), will I get Class.Test, or will I get the child class (e.g. Class.A)? Is it possible for the Driver class to know x’s subclass?

Is it possible to create a method like:

public Class getSubclassFromLetter(Letter x) < // Find subclass from the letter >

You can use instanceof . It is not really a good practice to do that, but you can do the following:

using either instanceof or Class#getClass()

A returned = getA(); if (returned instanceof B) < .. >else if (returned instanceof C)

getClass() would return either of: A.class , B.class , C.class

That said, sometimes it is considered that using instanceof or getClass() is a bad practice.

Java — how to check if an instance of an abstract object, instanceof operator can be used to check if an object is an instance of a particular class. This matches your intent. You can achieve similar functionality with ClassA.isAssignableFrom (ClassB). Here, …

Check if subclass implements an interface in parent class?

I know how to check if an object implements an interface. But how do I check in the parent class if the subclass implements the interface?

class B extends A implements Listener

Here B implements the interface Listener but C does not. How do I check it?

this or Object.getClass() returns the reference respectivly the Class object at runtime.
So you can use them to check whether the object or the class implements a specific interface.

If you manipulate classes :

if (Listener.class.isAssignableFrom(C.class))

If you manipulate instances :

if (this instanceof Listener)

You can check in the parent class if the this variable implements your Listener -interface, because the this -variable references to the actual subclass object:

So above code block will be executed for the subclass B but not for C

You can just have a method like this in A :

public void maybeAddListener() < if (this instanceof Listener) < somethingOrAnother.addListener((Listener) this); >> 

Whether or not that’s a good idea depends on what exactly you want to achieve with this. If subclasses of A are likely to implement Listener then a better idea is to just implement it in A with a do-nothing implementation and let subclasses override the appropriate methods.

What I can think of right now is creating an object of that class and checking with

 object instanceof interface 
 object.getClass().getInterfaces() 

How to check type of class in Java?, You can use instanceof keyword to check type of object in java. For example : public class Stack < public Stack () < >public static void main (String [] args) < Stack s1 = new Stack (); System.out.println (s1 instanceof Stack); >> In you code you can do something like this:

Читайте также:  Php amocrm api отправка формы

Check conditions in subclass before calling superclass constructor method

As we know in the constructor body of a subclass, the parent constructor must be the first statement otherwise we get a compile time error, This topic is already discussed here.

Let’s assume that calling the parent constructor causes a heavy cost of system resources, In other hand in the subclass constructor we need to check some conditions first, if the conditions are satisfied we’re good to go through the parent constructor else there’s no need to go further (let’s say throw an exception):

class parent < parent(Object blah) < //Heavy resource consuming tasks >> class child extends parent < child(Object blah, boolean condition) < if (!condition) throw new IllegalArgumentException("Condition not satisfied"); super(blah); //Compile error! >> 

If someone had the same issue I’m curious is there anyway to handle this situation or I must call the parent constructor first no matter how much resources it wastes and then throw the exception?

You could do something like this:

public class Jlaj extends ArrayList  < public Jlaj(int capacity) < super(checkCapacity(capacity)); >private static int checkCapacity(int capacity) < if (capacity >1000) throw new IllegalArgumentException(); return capacity; > public static void main(String[] args) < new Jlaj(1001); // this throws IAE all right >> 

Note that you can only call static methods in this fashion, and that’s good: calling instance methods on a partially initialized object is already a huge trouble, calling them even before superclass constructors would be a nightmare.

Now what if you need to check some other arguments that you don’t pass to the superclass? You could do something like this then:

public class Jlaj extends ArrayList  < private final Object foo; public Jlaj(int capacity, Object foo) < super(checkArgumentsAndReturnCapacity(capacity, foo)); this.foo = foo; >private static int checkArgumentsAndReturnCapacity(int capacity, Object foo) < if (capacity >1000) throw new IllegalArgumentException(); if (foo == null) throw new NullPointerException(); return capacity; > public static void main(String[] args) < new Jlaj(1000, null); // throws NPE >> 

It works, but looks a bit ugly. You’re passing two unrelated things into a function that returns just an argument for the superclass. At least the descriptive name somewhat compensates for that.

if you absolutely need to do this, you can create a static builder method with a private constructor:

class child extends parent < private child(Object blah) < super(blah); >static child create(Object blah, boolean condition) < if (!condition) throw new IllegalArgumentException("Condition not satisfied"); return new child(blah); >public static void main(String[] args) < child a = child.create("a", true); >> 

I’m not a fan of a separate init method because you will end up with invalid state if you forget to call it.

Checking if a Class object is a subtype of another Class, Let’s say I have two Class objects. Is there a way to check whether one class is a subtype of the other? public class Class1 < >public class Class2 extends Class1 < >public class Main < Classclazz1 = Class1.class; Class clazz2 = Class2.class; // If clazz2 is a subtype of clazz1, do something. > java …

Источник

Оцените статью