Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java equivalent of c# typeof()

I'm very new to java. Say I've a xml parser and I'd create object from it. In c# i'd do like:

parser p = new parser(typeof(myTargetObjectType));

In my parser class I need to know which object I'm making, so that i can throw exception if parsing is not possible. How to Do the same in jave? I mean how I can take arguments like typeof(myObject)


I understand every language has it's own way of doing something. I'm asking what's way in java

like image 487
deeiip Avatar asked Feb 13 '23 08:02

deeiip


2 Answers

Java has the Class class as the entry point for any reflection operation on Java types.

Instances of the class Class represent classes and interfaces in a running Java application

To get the type of an object, represented as a Class object, you can invoke the Object#getClass() method inherited by all reference types.

Returns the runtime class of this Object.

You cannot do this (invoke getClass()) with primitive types. However, primitive types also have an associated Class object. You can do

int.class

for instance.

like image 71
Sotirios Delimanolis Avatar answered Feb 23 '23 01:02

Sotirios Delimanolis


public class Main {
  public static void main(String[] args) {
    UnsupportedClass myObject = new UnsupportedClass();
    Parser parser = new Parser(myObject.getClass());
  }
}

class Parser {
  public Parser(Class<?> objectType) {
    if (UnsupportedClass.class.isAssignableFrom(objectType)) {
          throw new UnsupportedOperationException("Objects of type UnsupportedClass are not allowed");
    }
  }
}

class UnsupportedClass {}

Or since you have the instance of the object, this is easier:

Parser parser = new Parser(myObject);

public Parser(Object object) {
    if (object instanceof UnsupportedClass) {
          throw new UnsupportedOperationException("Objects of type UnsupportedClass are not allowed");
    }
}
like image 44
Savvas Dalkitsis Avatar answered Feb 22 '23 23:02

Savvas Dalkitsis