How to determine an object's class?
if (obj instanceof C) {
//your code
}
how to determine class of an object
The "correct way" to determine the S3 class of an object is using function class
.
Implicit classes:
class(list(1))
#[1] "list"
class(1:5)
#[1] "integer"
Explicit classes:
class(list(1))
class(lm(Sepal.Length ~ Sepal.Width, data = iris))
#[1] "lm"
x <- 1:5
class(x) <- "myclass"
class(x)
#[1] "myclass"
Since a list can contain anything, you have to loop through it to find out the classes of the objects inside it, e.g., sapply(yourlist, class)
.
The class ID is stored as an attribute (as are names, dimensions and some other stuff), but usually you don't need to worry about such internals, since R offers accessor functions.
Check if an object belongs to a class in Java
The instanceof
keyword, as described by the other answers, is usually what you would want.
Keep in mind that instanceof
will return true
for superclasses as well.
If you want to see if an object is a direct instance of a class, you could compare the class. You can get the class object of an instance via getClass()
. And you can statically access a specific class via ClassName.class
.
So for example:
if (a.getClass() == X.class) {
// do something
}
In the above example, the condition is true if a
is an instance of X
, but not if a
is an instance of a subclass of X
.
In comparison:
if (a instanceof X) {
// do something
}
In the instanceof
example, the condition is true if a
is an instance of X
, or if a
is an instance of a subclass of X
.
Most of the time, instanceof
is right.
How to identify object types in java
You forgot the .class
:
if (value.getClass() == Integer.class) {
System.out.println("This is an Integer");
}
else if (value.getClass() == String.class) {
System.out.println("This is a String");
}
else if (value.getClass() == Float.class) {
System.out.println("This is a Float");
}
Note that this kind of code is usually the sign of a poor OO design.
Also note that comparing the class of an object with a class and using instanceof is not the same thing. For example:
"foo".getClass() == Object.class
is false, whereas
"foo" instanceof Object
is true.
Whether one or the other must be used depends on your requirements.
How to get a JavaScript object's class?
There's no exact counterpart to Java's getClass()
in JavaScript. Mostly that's due to JavaScript being a prototype-based language, as opposed to Java being a class-based one.
Depending on what you need getClass()
for, there are several options in JavaScript:
typeof
instanceof
obj.
constructor
func.
prototype
,proto
.isPrototypeOf
A few examples:
function Foo() {}
var foo = new Foo();
typeof Foo; // == "function"
typeof foo; // == "object"
foo instanceof Foo; // == true
foo.constructor.name; // == "Foo"
Foo.name // == "Foo"
Foo.prototype.isPrototypeOf(foo); // == true
Foo.prototype.bar = function (x) {return x+x;};
foo.bar(21); // == 42
Note: if you are compiling your code with Uglify it will change non-global class names. To prevent this, Uglify has a --mangle
param that you can set to false is using gulp or grunt.
java - How do I check if my object is of type of a given class?
I think you want aClass.isInstance( v2 )
. The docs say it works the same as the instanceOf
keyword. I guess they can't use instanceOf
as a method name because keywords can't be used as method names.
v2 = ???
Volvo v1 = new Volvo();
Class aClass = v1.getClass();
aClass.isInstance( v2 ) // "check(aClass)"
Or maybe just use a class literal, if "Volvo" is a constant.
v2 = ???
Volvo.class.isInstance( v2 );
Determine the type of an object?
There are two built-in functions that help you identify the type of an object. You can use type()
if you need the exact type of an object, and isinstance()
to check an object’s type against something. Usually, you want to use isinstance()
most of the times since it is very robust and also supports type inheritance.
To get the actual type of an object, you use the built-in type()
function. Passing an object as the only parameter will return the type object of that object:
>>> type([]) is list
True
>>> type({}) is dict
True
>>> type('') is str
True
>>> type(0) is int
True
This of course also works for custom types:
>>> class Test1 (object):
pass
>>> class Test2 (Test1):
pass
>>> a = Test1()
>>> b = Test2()
>>> type(a) is Test1
True
>>> type(b) is Test2
True
Note that type()
will only return the immediate type of the object, but won’t be able to tell you about type inheritance.
>>> type(b) is Test1
False
To cover that, you should use the isinstance
function. This of course also works for built-in types:
>>> isinstance(b, Test1)
True
>>> isinstance(b, Test2)
True
>>> isinstance(a, Test1)
True
>>> isinstance(a, Test2)
False
>>> isinstance([], list)
True
>>> isinstance({}, dict)
True
isinstance()
is usually the preferred way to ensure the type of an object because it will also accept derived types. So unless you actually need the type object (for whatever reason), using isinstance()
is preferred over type()
.
The second parameter of isinstance()
also accepts a tuple of types, so it’s possible to check for multiple types at once. isinstance
will then return true, if the object is of any of those types:
>>> isinstance([], (tuple, list, set))
True
Find object's class
As a disclaimer, I'm not going to write the rule for you. Everything should be available from the API (syntax or semantic)... Once correctly formulated your requirement in term of rule writing and concepts.
To reformulate the requirement: You are trying to verify that the class (the object...) owning the called method is a DAO (a.k.a. the owner), and if it's the case, raise an issue (if it's within a loop, but that's another story).
Now, from the methodInvocationTree
itself that you already have, access its associated symbol
(there is a symbol()
method in the API), then it's owner
symbol, which should be the owning class. From the owner symbol, you can then access directly its name
, and validate if it contains "Dao".
Put into code:
boolean methodFromDao = methodInvocationTree
.symbol()
.owner()
.name()
.contains("Dao");
Important note: From the syntax API, you used another level of abstraction from the SonarJava API, which gives you access to symbols. In order to complete the semantic, SonarJava requires access to bytecode during analysis. If bytecode is not provided, it is most likely that methods won't be resolved by the semantic engine. Concretely, it means that all the symbols will be unknown
, and you won't be able to know their owners.
Related Topics
Map Implementation with Duplicate Keys
Java Reading a File into an Arraylist
How to Get the Exact Middle of a Screen, Even When Re-Sized
How to Convert a Stack Trace to a String
Intellij Inspection Gives "Cannot Resolve Symbol" But Still Compiles Code
How to Merge Two Sorted Arrays into a Sorted Array
What Is Suppresswarnings ("Unchecked") in Java
Why Is There No Multiple Inheritance in Java, But Implementing Multiple Interfaces Is Allowed
Hibernate JPA Sequence (Non-Id)
How to Load a Jar File at Runtime
Are Static Fields Open for Garbage Collection
How to Parse a Mathematical Expression Given as a String and Return a Number
Auto Errors Detection in Intellij Idea
Implementing Two Interfaces in a Class with Same Method. Which Interface Method Is Overridden