Questions tagged [instanceof]

instanceof is an operator available in some object-oriented languages, including Java, php and JavaScript. Generally speaking, it allows the programmer to check whether an object passed as its left operand is an instance of a class specified by the right operand.

Filter by
Sorted by
Tagged with
-1 votes
1 answer
67 views

instanceof cannot be used with any class? [duplicate]

I am trying instanceof in Java. I declared three classes where one extends another as follows: class ParentClass { // Class members } class ChildClass extends ParentClass{ // Class members } ...
Osama El-Ghonimy's user avatar
1 vote
1 answer
63 views

Difficulty Identifying Custom Exception Type in TypeScript throw Statement

I've encountered an issue while working with a custom HttpException class in TypeScript. Here's the structure of the class: class HttpException extends Error { public status: number | undefined; ...
Roni Jack Vituli's user avatar
0 votes
0 answers
78 views

Pattern Matching for instanceof - compile-time error for a [type] instanceof [subtype]

Reading this JDK Enhancement Proposal for Pattern Matching for instanceof: https://openjdk.org/jeps/394 Make it a compile-time error for a pattern instanceof expression to compare an expression of ...
zeugor's user avatar
  • 832
-2 votes
2 answers
128 views

How to avoid instanceof

I have interface AAA. I have two classes (entities): public class BBB implements AAA public class CCC implements AAA Both classes have different fields of course that will be used in Service I have ...
Matley's user avatar
  • 2,003
2 votes
2 answers
282 views

instanceof Pattern matching in Java, not compiling

Below is a paragraph taken from 'Java - The Complete Reference' book, 12th edition. Number myOb = Integer.valueOf(9); int count = 10; if((count < 100) && myOb instanceof Integer iObj) { //...
Flavian Diol D's user avatar
0 votes
1 answer
83 views

Why does pattern matching with instanceof fail to compile when using the boolean logical operator &?

When using instanceof as a pattern match operator in an if-statement, the code fails to compile if we use the boolean logical operator &, but succeeds if using &&. This DOES compile: ...
Lilypad's user avatar
  • 129
0 votes
2 answers
69 views

Using instanceof in if statement

if(objectName instanceof Mammal currentMammal){ currentMammal.shedHair(); if the (objectName instanceof Mammal) is true then currentMammal is casted to Mammal. I see this works, but dont know how....
Z H.KHAN's user avatar
0 votes
1 answer
42 views

List of objects implementing an interface and interface extension

If I have an interface A and an interface B that extends A. In a List of A how can I recognise the objects that implement B and so call the methodB of interface B on them? public interface A{ void ...
sco's user avatar
  • 3
-3 votes
1 answer
95 views

Java instanceof magic

There is such a method: static void test(List<String> list) { System.out.println(list); if (!(list instanceof ArrayList<String> arrayList)) return; System.out.println(list == ...
Leonis's user avatar
  • 294
0 votes
1 answer
44 views

Java: instanceof doesn't compile [duplicate]

I'm a newbie to Java and want to write a method checking if this object is of a sub class of given class <p_SuperClassName>. Eclipse denies compilation of the following code giving the message ...
tswd's user avatar
  • 1
1 vote
1 answer
72 views

TypeScript: using instanceof with and without "===true"

Let's consider this simple statement : var foo = document.getElementById('foo'); if (foo instanceof Element) { a.innerHTML = "Some text"; } But if you write : var foo = document....
Mulot's user avatar
  • 281
0 votes
2 answers
199 views

instanceof operator and this.constructor.name showing parent class name even it is child class in typescipt

Instanceof operator and this.constructor.name showing parent class name even it is child class in typescipt. I defined a class that extends default typescript error class export default class ...
Hossam Hamza's user avatar
0 votes
2 answers
75 views

Java: Filter items that are comparable to a wildcard type

I'm writing an interpreter for a DSL and I ran into a problem where I want to compare two values of unknown type. I have tried to reduce the problem to the following. I want to define a function with ...
Safron's user avatar
  • 802
5 votes
1 answer
568 views

Why does the `instanceof` operator return false on instance passed to library? (No inheritance involved)

I am building a library with TS. This library uses the ssh2 library as a dependency. I'm trying to create a function that can either accept an ssh2 configuration object or an already existing Client ...
Kerim Güney's user avatar
  • 1,138
0 votes
1 answer
70 views

Referencing an interface from ArrayList

I am having trouble understanding ((Edible)objects[i]).howToEat() at line 7 in the java code example given below. Edible is an interface which contains abstract method howToEat() and I understand that ...
ProgrammingStudent's user avatar
0 votes
0 answers
234 views

The URL constructor is not returning a TypeError when passed an invalid URL

Environment Node v19.0.0 Applied @babel/preset-typescript Applied @babel/preset-env tsconfig.json target set to ES6 Background The below code has a try/catch block where if the new URL constructor ...
Dave's user avatar
  • 31
1 vote
0 answers
45 views

Typescript's instanceof ignores initial type

When i want to check if a function parameter is a derived class, the instanceof operator allows me to compare it against virtually any class, ignoring the fact that class Random is completely ...
BMFreed's user avatar
  • 11
0 votes
1 answer
2k views

Java (14 and above) instanceof cast to generics (e.g. List<String> )

I'm deserializing JSON payloads using Jackson. I have some fields that can be either Objects or Arrays of Objects. So In my Java code I'm declaring class Outer{ private Object inner; } I know ...
johnmerm's user avatar
  • 696
0 votes
1 answer
52 views

How to create a generic instanceof function that returns the object if it's an instance of that type?

I'm basically trying to write a function like this: function isInstance<T>(s: T): T | boolean { return (s instanceof T) && s; } Where if it is the instance, it returns the value as ...
Ryan Peschel's user avatar
  • 11.3k
1 vote
1 answer
2k views

Record implementing Interface returns false when checked using instanceof (spring-boot, Java 19)

Code example is below. I have a Record that implements an Interface. When I check if an object of type Record is an instanceof the Interface, the result is false. Is there any special Java behavior ...
martinspielmann's user avatar
1 vote
2 answers
72 views

Instanceof does not work when I use @EJB, why is that?

I got two interface-classes (actually three) in a maven project called "interface": @Local public interface CrudSessionLocal extends CRUDS { } public interface ExceptionThrower { ...
user2902165's user avatar
0 votes
1 answer
92 views

What are unconditional patterns? (Java 19) [preview] unconditional patterns in instanceof are a preview feature and may be removed in a future release

I am working in Java 19, and using the pattern matching for instanceof that was released in JEP 394 (which released in Java 16). However, I am running into a warning that I am struggling to understand....
davidalayachew's user avatar
3 votes
2 answers
1k views

Pattern Matching for instanceof throwing a confusing error: expression type Triple is a subtype of pattern type Triple

I have Java 19, and I am attempting to do some simple pattern-matching on a record that I created. However, Java is giving me a very confusing compilation error. Here is the simplest example I could ...
davidalayachew's user avatar
0 votes
0 answers
36 views

inference error when testing each element of a mixed-type list with "instanceof" in a ternary operator on a stream() in Java

I know this could be a design flaw in Java, but I'd like to process a list with unknown types (easy to do in Python), mapping each element with a lambda function that tests the type and outputs ...
Rafael's user avatar
  • 41
0 votes
1 answer
343 views

Java instanceof with Object

I have a spring boot project with Java 17. I am calling a third party API to get the list of records. If the records are present I do get the 200 OK response with list of records and in case records ...
anonymous's user avatar
  • 183
1 vote
1 answer
99 views

Why does typechecking with 'instanceof' works differently for logical not operator and strict false equality check?

I have the following code: function handleIndexClick(event: MouseEvent) { if (event.target instanceof HTMLElement === false) { return; } // here will be a type error: Property 'dataset' ...
aantropov's user avatar
0 votes
1 answer
191 views

Combining assert statement and instanceof pattern matching

In Java 19, I'm trying to use instanceof pattern matching inside an assert statement. I would expect the matched type would be available after the statement, but the Java compiler does not recognize ...
werkderk's user avatar
1 vote
0 answers
157 views

instanceof checkcast secondary_super_cache jvm bug

There's been some posts and talks recently about this issue https://bugs.openjdk.org/browse/JDK-8180450. Posts https://netflixtechblog.com/seeing-through-hardware-counters-a-journey-to-threefold-...
Steven Dallas's user avatar
3 votes
1 answer
460 views

Applying Pattern matching for Instanceof in the Stream

Suppose we have a Stream of Animals. We have different Subclasses of Animals, and we want to apply a filter on the stream to only have the Zebras of the Stream. We now still have a Stream of Animals, ...
Dario Viva's user avatar
1 vote
3 answers
601 views

python Selenium taking instance of webdriver

i defined two separate functions for opening url with selenium, and fetching data with selenium. In my second function driver variable is unassignable because it stays local inside first function. I ...
xlmaster's user avatar
  • 679
0 votes
4 answers
110 views

Generic method using instanceof and can it be avoided?

I have the following generic interface/classes public interface AnInterface <T>{ T convertToY(); String getName(); String getLastName(); } public class Foo implements AnInterface&...
Jim's user avatar
  • 3,949
0 votes
1 answer
700 views

Angular 13 : how to get http request body object type?

I don't know if my question is legit or not, but I am trying to intercept every message from my api for dispose it in a popup via an interceptor : export class ApiMessageInterceptor implements ...
Raikho's user avatar
  • 13
4 votes
1 answer
334 views

Understanding TS' type inferring/narrowing with combination of extends & implements

I have the following example code class B implements Error { name: string = ''; message: string = ''; // stack?: undefined | string; } function Foo(x: any) { if(x instanceof Error) { if(x ...
Juarrow's user avatar
  • 2,274
0 votes
3 answers
247 views

Why doesn't "instanceof Mixin(Class)" work?

Why doesn't this work? (Checking instanceof an applied mixin) <script type="text/javascript"> class Bar {} const Foo = (classToExtend) => class extends classToExtend {}; ...
Dan's user avatar
  • 764
7 votes
4 answers
974 views

Java Pattern Variable Scope

I am going through Oracle's official docs to understand Pattern Variable scope in Java 17. In the following example, the method testScope1 works as explained in the docs, but the method testScope2 ...
Steve's user avatar
  • 909
2 votes
1 answer
62 views

Can a POST value ever be an instanceof something in PHP?

I've come across PHP code with the a check which tests if a POST value is an instanceof a class: if ($_POST['something'] instanceof SomeClass) { // do something } This seems odd to me, because I ...
tim's user avatar
  • 1,999
0 votes
1 answer
109 views

Using instanceof to seperate classes in an ArrayList

apologies if this is simple or has been answered before, I'm new to Java and in my research I can't find too much on this issue and have not yet found a solution. I have an ArrayList with multiple ...
MrYummy8626's user avatar
0 votes
1 answer
100 views

instanceof returns false in jdbc

I have problem with instanceof in java. For clarification, I use aws-neptune-jdbc drive for connection to janusgraph server. I create GraphSONMessageSerializerV3d0 which is obviously instance of ...
Makar Selivanov's user avatar
0 votes
4 answers
113 views

Java: Can instanceof also check "enclosing classes"?

Is instanceof able to check also the enclosing class (not sure if that is the right wording for my problem)? Please see below. Car.java public class Car { public static class Wheel {} } class ...
chris01's user avatar
  • 11.2k
0 votes
1 answer
1k views

Unable to check if thrown error is an instance of a custom error class

I have created a custom error class which extends the built-in Error class and adds a new value to it. The error itself works as expected. I want to handle this error explicitly when I catch it. This ...
Tomas Mačiulis's user avatar
1 vote
0 answers
24 views

Detect object literal being a serialization of a class [duplicate]

I am looking for a way to detect if an object literal is in fact a "non-instantiated" object of a certain class. I hope it will be more clear with an example: class Range{ from: number; ...
tru7's user avatar
  • 6,582
1 vote
1 answer
87 views

How can I identify the class of an abstract object being an argument to a function?

I am trying to make a function that sifts through an array of objects that inherit from one abstract class. The function takes in the item to look for as an argument of the abstract class type, and, ...
Axsis's user avatar
  • 23
0 votes
0 answers
60 views

Matched object type miss when expression case. Kotlin

It just blew my mind. So maybe someone was faced with such a problem. I try to use a new approach for Retrofit with statements. The problem is that even with a matched instance of the result else ...
Eugene Troyanskii's user avatar
0 votes
0 answers
38 views

Does c# have a method like instanceof() [duplicate]

There is a operator in java to check whether one object is an instance of a class or of that type. Is there a method similar to this in c#. Or do we create a custom method that does that.
The_emporer's user avatar
0 votes
0 answers
58 views

How to make HashMap of Classes in Java

I'm trying to make a HashMap of Classes in Java, and it gives me inconsistent errors and doesn't want to compile... Is it even possible to do this? package com.something; import java.util.HashMap; ...
sunrize531's user avatar
2 votes
1 answer
404 views

Use Class<?> parameter in instanceof method

I have the following method that can return different types of Storable (ex: Food, Ore). Inventory.java public Storable get(Class<? extends Storable> cls) { for (Storable storable : ...
Zerak's user avatar
  • 38
1 vote
2 answers
898 views

How to filter out Distinct objects of a Particular subtype from a List of super type with Streams

I would like to create a Java stream that will collect only elements that are instanceof class A and at the same time are distinct by x. I am using Java 8. What I have in the beginning is a List of ...
zaoras's user avatar
  • 61
0 votes
3 answers
57 views

Passing class to use instanceof in a function

I have a class structure: class BonusCard{ } class AddResourceCard extends BonusCard{ } class AddGoldCard extends BonusCard{ } Now, I also have a function in which I want to pass AddResourceCard ...
D idsea J's user avatar
  • 113
1 vote
2 answers
702 views

Is it acceptable to rethrow Exception's cause?

Sometimes I would want to throw an exception with more information to the user, so they can easily see why the method failed. My method would look like this: public myPublicMethod(...) throws ...
kolorowa's user avatar
0 votes
3 answers
294 views

lodash's isElement equivalent in pure JS

Right now I am using isElement by lodash to check if an element is DOM likely. I want to get rid of this library so I am looking for a pure JS implementation of this function. I'm using this, but I ...
Emel's user avatar
  • 2,313

1
2 3 4 5
20