deeiip
deeiip

Reputation: 3379

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

Upvotes: 4

Views: 11326

Answers (2)

Savvas Dalkitsis
Savvas Dalkitsis

Reputation: 11592

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");
    }
}

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280102

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.

Upvotes: 8

Related Questions