Sergej Chodarev
Sergej Chodarev
Metaprogramovanie je vytváranie programov, ktoré manipulujú programami ako dátami — analyzujú, generujú alebo transformujú iné programy alebo seba.
One person’s data is another person’s program.
— Guy L. Steele, Jr.
Metaprogramovanie je vytváranie programov, ktoré manipulujú programami ako dátami — analyzujú, generujú alebo transformujú iné programy alebo seba.
computer program, detailed plan or procedure for solving a problem with a computer; more specifically, an unambiguous, ordered sequence of computational instructions necessary to achieve such a solution. The distinction between computer programs and equipment is often made by referring to the former as software and the latter as hardware.
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}

"Magic" is just a word programmers use for poetry in code that they don't appreciate at first glance. I love magic and learning how it works! We're supposed to be the wizards of the computer.
— DHH (@dhh) February 8, 2025
Reflexia (reflection) — schopnosť spusteného programu skúmať svoju štruktúru, stav a okolie a na základe toho meniť svoje správanie.
Introspekcia (introspection) — sebapozorovanie.
public class ReflectiveHelloWorld {
public void printHello() {
System.out.println("Hello from " +
this.getClass().getName());
}
}
Majme objekt o ktorom vieme, že má definovanú metódu void setColor(Color color), nevieme však jeho konkrétny typ.
Ako zavolať túto metódu?
public static void setObjectColor(Object obj, Color color) {
Class cls = obj.getClass();
try {
Method method = cls.getMethod("setColor", Color.class);
method.invoke(obj, color);
} catch (NoSuchMethodException ex) { ... }
catch (IllegalAccessException ex) { ... }
catch (InvocationTargetException ex) { ... }
}
Class, Method, Field, Constructor, atď.java.lang.reflectClass<?> Object.getClass()String.class
int.classClass<T>String getName()boolean isInterface()boolean isPrimitive()boolean isArray()Class<?>[] getInterfaces()Class<? super T> getSuperclass()Field[] getFields()Field[] getDeclaredFields()String getName()Class<?> getType()Object get(Object obj)void set(Object obj, Object value)Method[] getMethods()Method[] getDeclaredMethods()invoke(Object obj, Object... args)Constructor<T>
T newInstance(Object<?>... initargs)Class<T>
T newInstance()Field, Method, Constructorvoid setAccessible(boolean flag)field.setAccessible(true);