Trending December 2023 # Java Reflection Api Tutorial With Example # Suggested January 2024 # Top 16 Popular

You are reading the article Java Reflection Api Tutorial With Example updated in December 2023 on the website Achiashop.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Java Reflection Api Tutorial With Example

What is Reflection in Java?

Java Reflection is the process of analyzing and modifying all the capabilities of a class at runtime. Reflection API in Java is used to manipulate class and its members which include fields, methods, constructor, etc. at runtime.

The java.lang.reflect package provides many classes to implement reflection java.Methods of the java.lang.Class class is used to gather the complete metadata of a particular class.

Class in java.lang.reflect Package

Following is a list of various Java classes in java.lang.package to implement reflection-

Field: This class is used to gather declarative information such as datatype, access modifier, name and value of a variable.

Method: This class is used to gather declarative information such as access modifier, return type, name, parameter types and exception type of a method.

Constructor: This class is used to gather declarative information such as access modifier, name and parameter types of a constructor.

Modifier: This class is used to gather information about a particular access modifier.

Methods used in java.lang.Class

Public String getName (): Returns the name of the class.

public Class getSuperclass(): Returns the super class reference

Public Class[] getInterfaces() : Returns an array of interfaces implemented by the specified class

Public in getModifiers (): Returns an integer value representing the modifiers of the specified class which needs to be passed as a parameter to “public static String toString (int i )” method which returns the access specifier for the given class.

How to get complete information about a class

To get information about variables, methods, and constructors of a class, we need to create an object of the class.

public class Guru99ClassObjectCreation { public static void main (String[] args) throws ClassNotFoundException { Class c1 = Class.forName("Guru99ClassObjectCreation"); Guru99ClassObjectCreation guru99Obj = new Guru99ClassObjectCreation(); Class c2 = guru99Obj.getClass(); Class c3= Guru99ClassObjectCreation.class; } }

Following example shows different ways to create object of class “class” :

Example 1 : How to get Metadata of Class

Following example shows how to get metadata such as: Class name, super class name, implemented interfaces, and access modifiers of a class.

We will get the metadata of below class named Guru99Base.class:

import java.io.Serializable; public abstract class Guru99Base implements Serializable,Cloneable { }

Name of the class is: Guru99Base

It’s access modifiers are: public and abstract

It has implemented interfaces: Serializable and Cloneable

Since it has not extended any class explicitly, it’s super class is: java.lang.Object

Below class will get the meta data of Guru99Base.class and print it:

import java.lang.reflect.Modifier; public class Guru99GetclassMetaData { public static void main (String [] args) throws ClassNotFoundException { Class guru99ClassObj = Guru99Base.class; system.out.println("Name of the class is : " +guru99ClassObj.getName()); system.out.println("Name of the super class is : " +guru99ClassObj.getSuperclass().getName()); class[] guru99InterfaceList = guru99classObj.getInterfaces(); system.out.print("Implemented interfaces are : "); for (Class guru99class1 : quru99 InterfaceList) { system.out.print guru99class1.getName() + " "); } system.out.println(); int guru99AccessModifier= guru99classObj.getModifiers(); System.Out.println("Access modifiers of the class are : " +Modifier.tostring(guru99AccessModifier)); } }

print the name of the class using getName method

Print the name of the super class using getSuperClass().getName() method

Print the name of the implemented interfaces

Print the access modifiers used by the class

Example 2 : How to get Metadata of Variable

Following examples shows how to get metadata of variable:

Here, we are creating a class named Guru99VariableMetaData .class with some variables:

package guru; public class Guru99VariableMetaData { public static int guru99IntVar1=1111; static int guru99IntVar2=2222; static String guru99StringVar2="Learning Reflection API"; }

Steps to get the metadata about the variables in the above class:

Create the class object of the above class i.e. Guru99VariableMetaData.class as below:

Guru99VariableMetaData guru99ClassVar = new Guru99VariableMetaData(); Class guru99ClassObjVar = guru99ClassVar.getClass();

Get the metadata in the form of field array using getFields() or getDeclaredFields() methods as below:

Field[] guru99Field1= guru99ClassObjVar .getFields(); Field[] guru99Fiel2= guru99ClassObjVar .getDeclaredFields();

getFields() method returns metadata of the public variable from the specified class as well as from its super class.

getDeclaredFields() method returns metadata of the all the variables from the specified class only.

    Get the name of the variables using “public String getName()” method.

    Get the datatype of the variables using “public Class getType()” method.

    Get the value of the variable using “public xxx get (Field)” method.

    Here, xxx could be a byte or short of any type of value we want to fetch.

    Get the access modifiers of the variables using getModifier() and Modifier.toString(int i) methods.

    Here, we are writing a class to get the metadata of the variables present in the class Guru99VariableMetaData .class:

    package guru; import java.lang.reflect.Field; public class Guru99VariableMetaDataTest { public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException { Guru99VariableMetaData guru99ClassVar = new Guru99VariableMetaData(); Class guru99ClassObjVar = guru99ClassVar.getClass(); Field[] guru99Field1= guru99ClassObjVar.getDeclaredFields(); for(Field field : guru99Field1) { System.out.println("Variable name : "+field.getName()); System.out.println("Datatypes of the variable :"+field.getType()); int guru99AccessModifiers = field.getModifiers(); System.out.printlln("Access Modifiers of the variable : "+Modifier.toString(guru99AccessModifiers)); System.out.println("Value of the variable : "+field.get(guru99ClassVar)); System.out.println(); system.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *") ; } } }

    Created class object for Guru99VariableMetaData.class

    Got all the metadata of the variables in a Field array

    Printed all the variable names in the class Guru99VariableMetaData.class

    Printed all the data types of the variables in the class Guru99VariableMetaData.class

    Printed all the access modifiers of the variables in the class Guru99VariableMetaData.class

    Printed values of all the variables in Printed all the data types of the variables in the class Guru99VariableMetaData.class

    Example 3 : How to get Metadata of Method

    Following examples shows how to get metadata of a method:

    Here, we are creating a class named Guru99MethodMetaData .class with some methods

    package guru; import java.sql.SQLException; public class Guru99MethodMetaData { public void guru99Add(int firstElement, int secondElement , String result) throws ClassNotFoundException, ClassCastException{ System.out.println("Demo method for Reflextion API"); } public String guru99Search(String searchString) throws ArithmeticException, InterruptedException{ System.out.println("Demo method for Reflection API"); return null; } public void guru99Delete(String deleteString) throws SQLException{ System.out.println("Demo method for Reflection API"); } }

    Steps to get the metadata about the methods in the above class :

    Create the class object of the above class i.e. Guru99MethodMetaData.class as below:

    Guru99MethodMetaData guru99ClassVar = new Guru99MethodMetaData (); Class guru99ClassObjVar = guru99ClassVar.getClass();

    Get method information in a Method array using getMethods() and getDeclaredMethods() method as below:

    Method[] guru99 Method 1= guru99ClassObjVar .get Methods(); Method [] guru99 Method 2= guru99ClassObjVar .getDeclared Method s();

    getMethods() method returns metadata of the public methods from the specified class as well as from its super class.

    getDeclaredMethods() method returns metadata of the all the methods from the specified class only.

    Get the name of the method using getName() method.

    Get the return type of the method using getReturnType() method.

    Get access modifiers of the methods using getModifiers() and Modifiers.toString(int i) methods.

    Get method parameter types using getParameterTypes() method which returns a class array.

    Get thrown exception using getExceptionTypes() method which returns a class array.

    Here, we are writing a class to get the metadata of the methods present in the class Guru99MethodMetaData.class:

    package guru; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class Guru99MethodMetaDataTest { public static void main (String[] args) { class guru99ClassObj = Guru99MethodMetaData.class; Method[] guru99Methods=guru99classObj.getDeclaredMethods(); for(Method method : guru99Methods) { System.out.println("Name of the method : "+method.getName()); System.out.println("Return type of the method : "+method.getReturnType()); int guru99ModifierList = method.getModifiers(); System.Out.printlin ("Method access modifiers : "+Modifier.toString(guru99ModifierList)); Class[] guru99ParamList= method.getParameterTypes(); system.out.print ("Method parameter types : "); for (Class class1 : guru99ParamList){ System.out.println(class1.getName()+" "); } System.out.println(); Class[] guru99ExceptionList = method. getExceptionTypes(); system.out.print("Excpetion thrown by method :"); for (Class class1 : guru99ExceptionList) { System.out.println (class1.getName() +" "): } System.Out.println(); system.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * "); } } }

    Created class object for Guru99MethodMetaData.class

    Got all the metadata of all the methods in a Method array

    Printed all the method names present in the class Guru99MethodMetaData.class

    Printed return types of the methods in the class Guru99MethodMetaData.class

    Printed all the access modifiers of the methods in the class Guru99MethodMetaData.class

    Printed parameter types of the methods in Guru99MethodMetaData.class

    Printed exceptions are thrown by methods in Guru99MethodMetaData.class

    Example 4 : How to get Metadata of Constructors

    Following examples shows how to get metadata of constructors:

    Here, we are creating a class named Guru99Constructor.class with different constructors:

    package guru; import java.rmi.RemoteException; import java.sql.SQLException; public class Guru99Constructor { public Guru99Constructor(int no) throws ClassCastException ,ArithmeticException{ } public Guru99Constructor(int no, String name) throws RemoteException ,SQLException{ } public Guru99Constructor(int no, String name, String address) throws InterruptedException{ } }

    Here, we are writing a class to get the metadata of the constructors present in the class Guru99Constructor.class:

    package guru; import java.lang.reflect.Constructor; public class Guru99ConstructorMetaDataTest { public static void main (String[] args) { Class guru99Class=Guru99Constructor.class; Constructor[] guru99ConstructorList = guru99Class.getConstructors(); for (Constructor constructor : guru99ConstructorList) { System.out.println("Constrcutor name : "+constructor.getName()); int guru99Modifiers= constructor.getModifiers(); System.Out.printlin ("Constrctor modifier : "+Modifier.toString(guru99Modifiers)); Class[] guru99ParamList=constructor.getParameterTypes(); System.out.print ("Constrctor parameter types :"); for (Class class1 : guru99ParamList) { System.out.println(class1.getName() +" "); } System. out.println(); Class[] guru99ExceptionList=constructor.getFxceptionTypes(); System.out.println("Exception thrown by constructors :"); for (Class class1 : guru99ExceptionList) { System.out.println(class1.getName() +" "); } System.out.println(); System.out.println("*******************************************"); } } }

    Created class object for Guru99Constructor.class

    Got all the metadata of all the constructors in a Constructor array

    Printed all the constructor’s names present in the class Guru99Constructor.class

    Printed all the access modifiers of the constructors in the class Guru99Constructor.class

    Printed parameter types of the constructors in Guru99Constructor.class

    Printed exceptions are thrown by constructors in Guru99Constructor.class

    Summary

    Reflection programming in java helps in retrieving and modifying information about Classes and Class members such variable, methods, constructors.

    Reflection API in Java can be implemented using classes in java.lang.reflect package and methods of java.lang.Class class.

    Some commonly used methods of java.lang.Class class are getName (), getSuperclass (), getInterfaces (), getModifiers () etc.

    Some commonly used classes in java.lang.reflect package are Field, Method, Constructor, Modifier, etc.

    Reflection API can access private methods and variables of a class which could be a security threat.

    You're reading Java Reflection Api Tutorial With Example

    Photoshop Layer Mask Tutorial With Example

    What is a Photoshop Layer Mask?

    Layer Mask is a very important part of Photoshop tools that gives the ability to hide and reveal parts of the layer without deleting them.

    This is very efficient and non-destructive way of working. And it helps designers to become more efficient and more creative.

    Let’s try to make an image with the help of layer mask .so that we can understand exactly what the layer mask works for.

    I want to make a movie poster for a wellknown Hollywood movie “Avengers”. so let’s start working on it.

    I’m using this image as background of the poster.

    These all are images which we are going to use in this poster.

    This is our background layer, and we will take all other images one by one and set them all in the sky portion of the background.

    So let’s take the first one. i’m choosing iron man first. because I want to put him at the middle of the sky.

    Scale the image and set it’s position properly.

    Then take a photoshop layer mask for the image. Then grab the brush tool with smooth round brush. set the brush size,and start painting on the image to hide unwanted part of the image.

    Look at the layer mask, its displays some black area in which you have painted,and the black color hides pixels.

    Now go for the next image “Captain America”. And do the same process as we have done before on iron man image.

    And do the same process again on the other 3 images which we are using In this file.

    Let’s speed it up.

    Now Put the ironman on the top of the layer panel. because it is on middle portion so it will not look good to be behind all other layers.

    See, the bottom edges of all images are still sharp so it is looking very bad. so grab the brush tool and make all bottom edges blur, so that all images can look properly merged.

    Once you have done with it, then select all five images and press CTRL + G to put them all in a single group.

    And change the blend mode of that group to “screen” and look it is nicely blended with the sky.

    Then make the image more effective with the help of “curve”.

    Now we need to give a title to this poster. i have one image that we can use in this poster.

    Scale and arrange the position of the image.

    Now take a layer mask for this image. and start painting with black color and smooth round brush on unwanted parts of the image.

    Remove that all black color around the name.

    And then change the blending mode to “linear dodge”.

    Drag it down below the curve layer.

    Now save the file and take a look of it.

    Its looks awesome.

    We designed this poster very quick and easily with the help of layer mask.

    So now just remember that black color hides pixels and white color reveals pixels.

    So now u can understand how much important is photoshop masking layer tool.

    This was the layer mask tool, now go ahead to the next topic “shape layer”.

    Split() String Method In Java: How To Split String With Example

    What is split() string in Java?

    StrSplit() method allows you to break a string based on specific Java string delimiter. Mostly the Java string split attribute will be a space or a comma(,) with which you want to break or split the string

    split() function syntax public String split(String regex) public String split(String regex, int limit) Parameter

    Regex: The regular expression in Java split is applied to the text/string

    Limit: A limit in Java string split is a maximum number of values in the array. If it is omitted or zero, it will return all the strings matching a regex.

    How to Split a String in Java with Delimiter

    Below example shows how to split string in Java with delimiter:

    Suppose we have a string variable named strMain formed of a few words like Alpha, Beta, Gamma, Delta, Sigma – all separated by the comma (,).

    Here if we want all individual strings, the best possible pattern would be to split it based on the comma. So we will get five separate strings as follows:

    Alpha

    Beta

    Gamma

    Delta

    Sigma

    Use the string split in Java method against the string that needs to be divided and provide the separator as an argument.

    In this Java split string by delimiter case, the separator is a comma (,) and the result of the Java split string by comma operation will give you an array split.

    class StrSplit{ public static void main(String []args){ String strMain = "Alpha, Beta, Delta, Gamma, Sigma"; String[] arrSplit = strMain.split(", "); for (int i=0; i < arrSplit.length; i++) { System.out.println(arrSplit[i]); } } }

    The loop in the code just prints each Java split string to array after the split function in Java, as shown below-

    Expected Output: Alpha Beta Delta Gamma Sigma Example: Java String split() method with regex and length

    Consider a situation, wherein you require only the first ‘n’ elements after the split function in Java but want the rest of the string to remain as it is. An output something like this-

    Alpha

    Beta

    Delta, Gamma, Sigma

    This can be achieved by passing another argument along with the split() string in Java operation, and that will be the limit of strings required.

    Consider the following code of split method in Java –

    class StrSplit2{ public static void main(String []args){ String strMain = "Alpha, Beta, Delta, Gamma, Sigma"; String[] arrSplit_2 = strMain.split(", ", 3); for (int i=0; i < arrSplit_2.length; i++){ System.out.println(arrSplit_2[i]); } } } Expected Output: Alpha Beta Delta, Gamma, Sigma How to Split a string in Java by Space

    Consider a situation, wherein you want to split a string by space. Let’s consider an example here; we have a split string Java variable named strMain formed of a few words Welcome to Guru99.

    public class StrSplit3{ public static void main(String args[]){ String strMain ="Welcome to Guru99"; String[] arrSplit_3 = strMain.split("\s"); for (int i=0; i < arrSplit_3.length; i++){ System.out.println(arrSplit_3[i]); } } } Expected Output: Welcome to Guru99

     

    How Does Angelscript Work With Example

    Introduction of AngelScript

    Start Your Free Software Development Course

    Web development, programming languages, Software testing & others

    Why do we Need AngelScript?

    AngelScript is needful because it is a powerful object-oriented scripting language like c/c++. It has an extremely flexible cross-platform scripting library; hence the scripts or a computer program written can work on any platform, and the scripting library is designed to improve the functionality of the script; by using it, users can extend the functionality with the help of external scripts.

    It also has a feature that we can call the c and c++ functions within the angel-script environment; due to that, it is helpful to the developers to work with it, and the syntax of the angel-script class was closely followed by the syntax in c++ classes. So that it is needful for developers who are worked with c++ and they have to work on angel-script, then they can work easily.

    Angelscript can be used in robotics that means the behavior rules of robotic are followed by angel-script. Also, it is useful for video game development, which increases the life of a game. So by using angle-script, get the project up, and that will run faster. And by using an external script, we can improve the functionality of the application.

    How does AngelScript Work?

    First, we need the application of angel-script and then have to register the interface so that script can interact with the application; the interface contains functions, variables, and classes also.

    Secondly, we have to set message call back to receive information about errors, errors in human-readable form, because if the registration is not done correctly, then attention message will get as a callback message about the incorrect registration or a script has an error that fails to compile. If we need to verify the return code, there is no need to take much effort to know it because the call-back message can give information in the human-readable form so that we can correct it. These two steps are about engine configuration.

    After engine configuration next step is to compile the script that should be executed. Also, need to write a function to call the registered print function and will give the output that function is stored in files.

    In this step, has to write code for loading script files and to compile it, there is a CSriptbuilder define it, which help to load the file, it will perform some necessary process, and it will tell the engine to build a script module, also need to construct builder code for processing. If the code fails after this, then it will not have the memory to allocate the module. If the filename has been removed or the wrong name was given, or there is some unnecessary code has been written, then the builder was not able to load the file.

    The last step is to identify the function which was defined that is to be called and have to set up the context for execution in code format. If that function could not be found, then need to write a print function to show a message of the function expecting.

    Then has to create context, prepare it, and then execute it; if the execution didn’t work as expected, there is a need to write an exception code to handle the exception.

    Example of AngelScript

    Below is a very simple example that will give a brief overview of Handle:

    }

    Advantages

    It has features like c/c++ that is static-typing, that uses the same static type as we use in c/c++ to make typing dynamic, and only additional type that we need to register here in angel-script.

    It has an object handle feature that provides pointers, but pointers are not safe in scripting; hence it uses object handles instead of pointers; object handles in scripting control the lifetime of the object.

    It has mod support in-game logic where it increases the life of the game.

    Angelscript supports native calling conventions on major platforms, but there are some platforms that only work with generic calling conventions; generic calling is pure C++ that works everywhere.

    The CScriptString used in angel-script cannot return the object value in native mode, which is not compatible.

    There may be a memory leak issue.

    Conclusion

    In this article, we conclude that it is a scripting language and that has information about the application to accurately communicate with the c/c++ code; it has an inbuilt library hence making scripting language in our project is easy; in this article, we have seen some reasons to develop our program in more than one language.

    Recommended Articles

    Sorted Set Interface In Java With Examples

    The Sorted Set interface has the term ‘Sorted’ in its name which signifies that it contains all the elements in ascending order. It extends the properties of the Set interface.

    In this article, we will discuss the sorted set interface and perform some operations on it. But, in order to understand the SortedSet properly we need to understand the hierarchy of collection interface.

    Collection Interface

    In java, collection is an object or we can say a container for simplicity that allows us to group several numbers of objects in a single unit. The collection interface is present at the root of all collection framework interfaces. We can perform various operations on collection like adding, removing, iterating, searching and retrieving objects. Note that they can’t work with primitive datatypes like int or double. However, java provides wrapper classes that enable the use of primitive datatypes as objects. We will use those objects to work with collection interface.

    Let’s discuss the sub interfaces of collection interface −

    List − It is the sub interface of Java Collection Interface. It is a linear structure that stores and accesses each element in a sequential manner.

    Set − It is the sub interface of Java Collection Interface that doesn’t allow duplicate values. It is similar to a mathematical set.

    Queue − It provides the features of queue data structure. Queue follows the First in First out (FIFO) approach.

    SortedSet Interface

    As we have discussed earlier that it stores elements in ascending order. Since it extends Set interface therefore, it also doesn’t allow duplicate values and it has access to all the methods provided by Set interface.

    Collection interfaces are available in ‘java.util’ package. To import this package into your program use the following command:

    import java.util.*;

    Here, ‘*’ signifies that we are importing all the classes available in this package.

    To use the features of SortedSet, we will use tree set class that implements SortedSet interface.

    Syntax

    Here, element_Type is the wrapper class not primitive datatypes.

    Other than the methods of Set interface it also includes the following methods −

    first() − It returns the object present at the first position.

    last() − It returns the object present at the last position.

    subSet() − It takes two arguments and prints all objects available between the given arguments.

    headSet() − It takes an argument and returns the objects from start to the specified argument.

    tailSet() − It takes an argument and returns the objects from specified argument to the end of set.

    Example 1

    In the following example, we will create a Tree Set named ‘treeSt’ of type string and using the inbuilt method ‘add()’ of collection interface, we will add a few elements to the Tree Set. It will print the elements in ascending order irrespective of the order of input elements.

    import java.util.*; public class Srtset { public static void main(String args[]) { treeSt.add("Tutorix"); treeSt.add("Simply"); treeSt.add("Easy"); treeSt.add("Learning"); treeSt.add("Tutorials"); treeSt.add("Point"); System.out.println("Elements of the given set: " + treeSt); } } Output Elements of the given set: [Easy, Learning, Point, Simply, Tutorials, Tutorix] Example 2

    The following example illustrates the use of all the inbuilt methods of SortedSet Interface we have discussed earlier in this article.

    import java.util.*; public class Srtset { public static void main(String args[]) { treeSt.add("Tutorix"); treeSt.add("Simply"); treeSt.add("Easy"); treeSt.add("Learning"); treeSt.add("Tutorials"); treeSt.add("Point"); System.out.println("Elements in the given set: " + treeSt); String frst = treeSt.first(); System.out.println("Accessing First element of the given set: " + frst); String end = treeSt.last(); System.out.println("Accessing Last element of the given set: " + end); System.out.println("Accessing subsets of the given set: " + treeSt.subSet("Simply", "Tutorix")); System.out.println("Accessing first two elements of set: " + treeSt.headSet("Point")); System.out.println("Accessing last three elements of set: " + treeSt.tailSet("Simply")); } } Output Elements in the given set: [Easy, Learning, Point, Simply, Tutorials, Tutorix] Accessing First element of the given set: Easy Accessing Last element of the given set: Tutorix Accessing subsets of the given set: [Simply, Tutorials] Accessing first two elements of set: [Easy, Learning] Accessing last three elements of set: [Simply, Tutorials, Tutorix] Conclusion

    Since objects are stored in sorted i.e. ascending order the access and retrieval time becomes faster in the case of SortedSet Interface. Because of this excellent feature, SortedSet is frequently used to store large amounts of information that needs to be searched quickly.

    Codeigniter Mvc(Model View Controller) Framework With Example

    What is MVC?

    MVC standards for Model-View-Control. It is an architectural pattern that splits the application into three major components.

    1. Model deals with business logic and database interactions

    2. Controller coordinates the activities between the model and the view

    3. View is responsible for data presentation

    Loose coupling -the components exist and function independently of each other.

    Flexibility – one can easily make changes to individual components

    Increased productivity – more than one person can work on the project at the same time. The front-end developers can work on views and presentation while backend developers can focus on models and since the system is loosely coupled, it works at the end of the day

    In this tutorial, you will learn:

    Model

    The model is responsible for interacting with data sources. This is usually a database, but it can also be a service that provides the requested data. It is also a common practice to have the business logic contained in the models as opposed to the controller. This practice is usually termed fat model skinny controller.

    The model usually writes data into the database, provides a mechanism for editing and updating, and deleting data. In a modern web application, models use data access design patterns such as active record to make interacting with the database easier.

    For example, CodeIgniter uses a built-in library Active Record to aid the models while other frameworks such as Laravel use Eloquent Object Relational Mapper (ORM) that aids data access.

    Controller

    The controller listens for incoming requests for resources from the users. It acts as the intermediate between the model and the view and at times implements some business rules as well. Let’s say the controller receives a request to register a user in the database.

    The controller may perform data validation on what has been submitted to ensure that all the required parameters have been submitted. If something is missing the user is redirected to the registration page with the appropriate error message displayed. The controller may also request the model to perform more validation by checking if the submitted email address already exists. If all validation rules pass then the controller submits the data to the model for process and waits for the response.

    View

    The view deals with data presented to the end user. In web applications, views often contain HTML, CSS, and optionally JavaScript. Views contain minimum programming code. The code contained in views is usually used to loop through collections of data received as parameters from the model or helper function for cleaning up data or creating links to edit the records. Most modern web application usually uses templating engines that define their own syntax which is more like pseudocode and can easily be understood by designers. When working with CodeIgniter, it is common practice to use short PHP tags and control structures. To display something in CodeIgniter, one might use the following code

    As opposed to

    <?php echo $title;

    Control structures are usually written as follows

    As you can see from the above example, the view will use a combination of PHP and HTML instead of enclosing everything in pure PHP code.

    How MVC frameworks work?

    The following image shows the MVC framework works

    A controller receives the request from the user, interacts with the database model if necessary then returns the result back to the browser in the form of HTML code which the browser interpreted into a human-readable format and displayed to the user.

    CodeIgniter Controller

    Let’s now breakdown what just happened when we loaded the above URL into the web browser.

    Open the file chúng tôi controller located application/controllers

    You should be able to see the following code

    <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Welcome extends CI_Controller { public function index() { } }

    HERE,

    defined(‘BASEPATH’) OR exit(‘No direct script access allowed’); prevents direct access to the controller if the request didn’t come through chúng tôi this is for security purposes.

    class Welcome extends CI_Controller {…} defines the Welcome controller class and extends the parent class CI_Controller

    We will now update the index method as follows

    public function index() { }

    HERE,

    CodeIgniter Model

    Let’s now create the view that we referenced in the above code. For simplicity’s, our model will not interact with the database but will return a static customer record. We will work with databases in the next tutorials.

    Create a file Customers_model.php in application/models

    Add the following code

    <?php class Customers_model extends CI_Model { public function get_customer($id) { $data['id'] = 3; $data['first_name'] = 'John'; $data['last_name'] = 'Doe'; $data['address'] = 'Kingstone'; return $data; } }

    HERE,

    class Customers_model extends CI_Model {…} defines the model Customers_model that extends CI_Model.

    public function get_customer($id) {…} defines the get customer method based on a customer id

    $data[…] defines the static values of our fictious customer. This should be a row returned from the database.

    return $data; returns the customer data.

    That is, it for our model. Let’s now modify the welcome_message view

    Open welcome_message.php located in

    application/views/welcome_message.php

    Replace the code with the following

    Save the changes

    Load the following URL in the web browser

    You should be able to see the customer card as shown in the image below

    Summary

    MVC is an architectural pattern that splits the application into three major components

    The model is responsible for interacting with data sources

    The controller listens for incoming requests for resources from the users

    In web applications, views often contain HTML, CSS, and optionally JavaScript

    A controller receives the request from the user, interacts with the database model if necessary then returns the result back to the browser in the form of HTML code

    Update the detailed information about Java Reflection Api Tutorial With Example on the Achiashop.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!