Технологии Java
Reflection
ArrayList.class
int.class
int[].class
| Тип класса | Метод |
|---|---|
| Верхнего уровня | getPackage() |
| Вложенный | getDeclaringClass() |
| в конструктор | getEnclosingConstructor() |
| в метод | getEnclosingMethod() |
| Константа | Метод | Модификатор |
|---|---|---|
| ABSTRACT | isAbstract(int) | abstract |
| FINAL | isFinal(int) | final |
| INTERFACE | isInterface(int) | interface |
| NATIVE | isNative(int) | native |
| PRIVATE | isPrivate(int) | private |
| PROTECTED | isProtected(int) | protected |
| PUBLIC | isPublic(int) | public |
| STATIC | isStatic(int) | static |
| STRICT | isStrict(int) | strictfp |
| SYNCHRONIZED | isSynchronized(int) | synchronized |
| TRANSIENT | isTransient(int) | transient |
| VOLATILE | isVolatile(int) | volatile |
Class c = …;
for (Field m : c.getDeclaredFields()) {
System.out.println(m);
}
for (Constructor m : c.getDeclaredConstructors()) {
System.out.println(m);
}
for (Method m : c.getDeclaredMethods()) {
System.out.println(m);
}
private final byte[] value
private final byte coder
static final boolean COMPACT_STRINGS
static final byte LATIN1
static final byte UTF16
private int hash
private boolean hashIsZero
private static final char REPL
private static final long serialVersionUID
private static final ObjectStreamField[]
serialPersistentFields
public static final Comparator
CASE_INSENSITIVE_ORDER
// Получение класса
Class<Random> clazz = Random.class;
// Получение конструктора
Constructor<Random> c =
clazz.getConstructor(long.class);
// Создание экземпляра
Random r = c.newInstance(100L);
// Проверка
System.out.println(r.nextInt());
| class | Lclass; |
| boolean | Z |
| byte | B |
| char | C |
| double | D |
| float | F |
| int | I |
| long | J |
| short | S |
URL url = Path.of(".").toUri().toURL();
ClassLoader cl = new URLClassLoader(new URL[]{url});
Class<?> c = cl.loadClass("Test");
Method m = c.getMethod("main", String[].class);
m.invoke(null, (Object) new String[]{"hello"});
Constructor<?> constructor = c.getConstructor();
Runnable instance =
(Runnable) constructor.newInstance();
instance.run();
public @interface TODO {
int id();
String synopsis();
String assignee() default "[unassigned]";
String date() default "[undefined]";
}
@TODO(
id = 123,
synopsis = "Implement",
assignee = "Georgiy Korneev",
date = "07.03.2025"
)
public static void giveLecture(String id, String title)
@MarkerAnnotation
@MarkerAnnotation()
@SingletonAnnotation("Hello")@SingletonAnnotation(value="Hello")
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test { }
public class SimpleTest {
@Test public static void testXXX();
@Test public static void testYYY();
}
for (Method m : clazz.getMethods()) {
if (m.isAnnotationPresent(Test.class)) {
try {
m.invoke(null);
} catch (Throwable e) {
System.out.printf("Test %s failed: %s %n",
m, e.getCause());
}
}
}
@Target(ElementType.TYPE_USE)
public @interface Attr { String value; }
public @interface Array { String value default "NONE"; }
@Array Map<
@Attr("id") Integer,
@Array("items") List<@Attr("value") String>
> values;
[
{id: 123, {items: [{value: "v1"}, {value: "v2"}]},
{id: 456, {items: []}
]
| Вид типа | Представление |
|---|---|
| Классы | Class |
| Параметризованный класс | ParameterizedType |
| Переменная типа | TypeVariable |
| Wildcard | WildcardType |
| Массивы | GenericArrayType |
public class Profiler implements
InvocationHandler {
// Экземпляр Proxy
private final Object instance;
// Реальная реализация
private final Object impl;
...
}
public Profiler(Class[] i8s, Object impl) {
this.impl = impl;
instance = Proxy.newProxyInstance(
null, i8s, this);
}
public Object getInstance() {
return instance;
}
public Object invoke(Object proxy,
Method method, Object[] args
) throws IllegalAccessException,
InvocationTargetException {
System.out.println(
"Calling " + method + " on " + impl);
return method.invoke(impl, args);
}
public static void main(String[] args) {
Integer i1 = new Integer(3);
Profiler profiler = new Profiler(
new Class[]{Comparable.class}, i1);
Comparable i2 =
(Comparable) profiler.getInstance();
System.out.println(i2.compareTo(i1));
}
MethodHandle loop = MethodHandles.whileLoop(
// init
MethodHandles.constant(long.class, 5),
// static boolean pred(i, step, limit) { return i < limit; }
find("pred", boolean.class, long.class, int.class, int.class),
// static long step(i, step, limit) { return i + step; }
find("step", long.class, long.class, int.class, int.class)
);
loop.invoke(10, 23); // 25
loop.invoke(3, 23); // 23