python3-10.pyscalpel.java.import_java

 1import os
 2
 3from typing import cast, Type, TypeVar
 4from functools import lru_cache
 5from sys import modules
 6
 7from pyscalpel.java.object import JavaObject
 8
 9
10@lru_cache
11def _is_pdoc() -> bool:  # pragma: no cover
12    return "pdoc" in modules
13
14
15ExpectedObject = TypeVar("ExpectedObject")
16
17
18def import_java(
19    module: str, name: str, expected_type: Type[ExpectedObject] = JavaObject
20) -> ExpectedObject:
21    """Import a Java class using Python's import mechanism.
22
23    :param module: The module to import from. (e.g. "java.lang")
24    :param name: The name of the class to import. (e.g. "String")
25    :param expected_type: The expected type of the class. (e.g. JavaObject)
26    :return: The imported class.
27    """
28    if _is_pdoc() or os.environ.get("_DO_NOT_IMPORT_JAVA") is not None:
29        return None  # type: ignore
30    try:  # pragma: no cover
31        module = __import__(module, fromlist=[name])
32        return getattr(module, name)
33    except ImportError as exc:  # pragma: no cover
34        raise ImportError(f"Could not import Java class {name}") from exc
def import_java( module: str, name: str, expected_type: Type[~ExpectedObject] = <class 'pyscalpel.java.object.JavaObject'>) -> ~ExpectedObject:
19def import_java(
20    module: str, name: str, expected_type: Type[ExpectedObject] = JavaObject
21) -> ExpectedObject:
22    """Import a Java class using Python's import mechanism.
23
24    :param module: The module to import from. (e.g. "java.lang")
25    :param name: The name of the class to import. (e.g. "String")
26    :param expected_type: The expected type of the class. (e.g. JavaObject)
27    :return: The imported class.
28    """
29    if _is_pdoc() or os.environ.get("_DO_NOT_IMPORT_JAVA") is not None:
30        return None  # type: ignore
31    try:  # pragma: no cover
32        module = __import__(module, fromlist=[name])
33        return getattr(module, name)
34    except ImportError as exc:  # pragma: no cover
35        raise ImportError(f"Could not import Java class {name}") from exc

Import a Java class using Python's import mechanism.

Parameters
  • module: The module to import from. (e.g. "java.lang")
  • name: The name of the class to import. (e.g. "String")
  • expected_type: The expected type of the class. (e.g. JavaObject)
Returns

The imported class.