/ Published in: Java
A nifty little example of reflection in Java using the Math class.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
//Main import javafx.application.Application; import javafx.collections.FXCollections; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.Button; import javafx.scene.layout.VBox; import javafx.stage.Stage; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.ArrayList; import java.util.Arrays; public class Main extends Application{ public static ArrayList<Method> validMethodList = new ArrayList<Method>(); public ArrayList<String> methodNameList = new ArrayList<String>(); launch(args); } public Scene createScene(){ VBox root = new VBox(); root.setSpacing(10); value.setId("value"); { Parameter parameter = method.getParameters()[0]; methodNameList.add(method.getName()); validMethodList.add(method); } } } ComboBox<String> methodComboBox = new ComboBox<String>(FXCollections.observableArrayList(methodNameList)); methodComboBox.setId("method"); btnCalc.setId("button"); lblAnswer.setId("answer"); root.getChildren().addAll(x, value, methodComboBox, btnCalc, lblAnswer); Scene scene = new Scene(root); return scene; } @Override primaryStage.setTitle("Reflection"); Scene scene = createScene(); primaryStage.setScene(scene); Controller controller = new Controller(); controller.connectSceneUI(scene); primaryStage.show(); } } //Controller import javafx.scene.Scene; import javafx.scene.control.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; public class Controller { ComboBox comboBox = new ComboBox(); public void connectSceneUI(Scene scene) { comboBox = (ComboBox) scene.lookup("#method"); button.setOnAction((event) -> { ArrayList<Method> validMethodList = nmmu.wrap301.Main.validMethodList; try { label.setText("Answer: " + answer.toString()); e.printStackTrace(); e.printStackTrace(); } }); } }