27. Java Reflections - Loading classes, constructors and methods at run time
In this video we will look at Java Reflections which is used to load classes, constructors and methods at run time.
Java Reflections – Loading Classes, Constructors and Methods at Run Time:
Java reflections package is used if we want to load any class, it’s constructor or methods at run time. In this one we only see what is needed for our selenium tutorials.
Here we created a package “actions” and a class under it called HomePage. We have created two static variables and a constructor to initialize those variables. We have also created four methods as well.
We have created another package “drivers” and class under it “ContactActions”. In this class we don’t create any object for HomePage class but we dynamically access this class and it’s constructor and methods at run time.
For accessing a class at run time, we use Class.forName() method. We have to pass the package name followed by “.” followed by class name. It returns a Class object. By writing Class ? , you're declaring a Class object which can be of any type (? is a wildcard). The Class type is a type that contains metainformation about a class.
Yu can get all the methods of the class by using getDeclaredMethods() which returns an array of public methods the class has. So we save all these in Method[].
Now you can print all the methods using Arrays.toString() method or you can loop through the Method[] array and print one by one.
To invoke any method first we have to load the method. This we do it with
Method mc = cls.getDeclaredMethod("getSumofTwoWithGlobal",int.class);
For loading a method we use getDeclaredMethod() and we have to pass the name of the method and type of variables the methoduse. If we use integer parameters in the method we use int.class and if we use string parameters it is string.class.
Next before invoking the method, we need to load the constructor. We use getConstructor() method and the variable types the constructor use.
Constructor ? constructor = cls.getConstructor(int.class, String.class);
Next, we invoke the method using invoke() method. We first pass the constructor.newInstance() as parameter and then the actual parameters the method use. Since this method returns an integer, we capture that in variable sum.
int sum = (int) mc.invoke(constructor.newInstance(1, "Selenium"), 2);
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «27. Java Reflections - Loading classes, constructors and methods at run time», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.