简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM