There is a method to which an object of any class can be passed as an argument, this method should check by means of instanceof to which class the object to be transferred belongs:
public class Alligator implements Predator {} public class Panda implements Herbivore {} public class Check{ Object naturalEnemy = new Alligator();// Проверяемый по умолчанию класс, !!!!может изменятся!!!!!! public static void main(String[] args){ System.out.println(""+checkAnimal(new Alligator()));// System.out.println(""+checkAnimal(new Panda())); } public boolean checkAnimal(Object animal){ if(naturalEnemy instanceof animal.getClass()) return true;// Не работает :( //if(naturalEnemy instanceof Predator) return true;// Работает, но подобный подход не приемлим. } } The catch is that none of the objects being compared is known, and it is also not acceptable to output the class in the text line. Help who than can. Thank you in advance.
obj instanceof java.lang.String, but we can'tClass<?> myclass = String.class; obj instamceof myclass;Class<?> myclass = String.class; obj instamceof myclass;(the code simply won't compile). But we can checkmyclass.isInstance(obj) ;so, for this check we don’t need a class instance, the class itself is enough, as you said - cache