SlideShare a Scribd company logo
REFLECTION IN JAVA
By: Zachary Cava
What exactly is a class?


It’s a collection of different things, such as:






Fields
Methods
Constructors

We define these different things with names,
types, parameters, values, expressions, etc
while programming, but in reflection all of this
already exists.
Programming vs Reflecting








We use reflection to manipulate things that
already exist and, normally, are set.
But unlike programming, we are not tied to
specific names, types or views.
We have the ability to dynamically change
what things are, regardless of how they were
written!
More specifically, we are modifying objects at
runtime.
What do you mean Runtime?


Normally you program something like this:






Write/Modify the class, methods, etc
Compile it
Run it

If you want to make any changes you have to
recompile and rerun that class.
What do you mean Runtime?


With reflection, we can manipulate a class
without ever recompiling it:







Write/Modify the class, methods, etc
Compile it
Run it
Modify the class here!

It is important to note that another class is the
one doing the modification.
Uses of Reflection


Some common uses of reflection:


To load and use classes unknown at compile
time, but have set methods.
 Example:





The Critters assignment

Test programs by forcing specific states
By debuggers to inspect running programs
Malicious things
 Hacking
Programming Reflection






To program with reflection, we must put on our
meta-thinking caps.
We are going to modify classes from classes
with classes!
To do this we have a great set of classes in
the following package:


java.lang.reflect.*;
Java.lang.reflect.*
Some classes we will go over, (there are more):
Method




Field




Describes a method for a class and gives access
to it.
Describes a field for a class, its type, name, etc.

Constructor<T>


Provides information about constructors and the
ability to execute a constructor and get a new
class instance
Java.lang.reflect.*


AccessibleObject




Describes the accessibility of an object, i.e. its
view public, private, protected, default.

Array


A special class created just for reflecting with
Arrays, since Arrays are such odd objects in Java
we must use this class to manipulate them.
So where do we start?


To start manipulating a class we must first get a
hold of that class’s “blueprint”.




There are two ways to do this, if the class is
already loaded:




Class<? extends Object> theClass = ClassName.class;

Or if we need to cause it to load:




Using the java.lang.Class class

Class theClass = Class.forName(“class.package”);

We won’t use this second one, its rather complex
at times.


Example Package: “java.lang.String”
So where do we start?







So now we have the definition of a class.
This is like the blueprint to the entire thing, it
lists where everything is and how to get to it.
It is important to point out that this class has
information that pertains to the structure of the
class, not specific instance information, but
hold that thought for a little later.
For now lets look at how to get some
information from the class
The Parts of the Class





Fields
Methods
Constructors
Miscellaneous
Getting those sweet fields


There are two ways to get class fields:


getFields();
 Returns

an array of Field objects, specifically all the
fields that are public for this class and its super
classes.



getDeclaredFields();
 Returns



an array of Field objects, regardless of view.

Optionally if you know the field name:


getField(String name);
 Returns

a Field with the given name
The Parts of the Class





Fields
Methods
Constructors
Miscellaneous
Calling all methods, report for
duty


Like Fields there are two ways to get Methods


getMethods();
 Returns

all the public methods for this class and any it
inherits from super classes.



getDeclaredMethods();
 Returns

of view.



all the methods for this class only regardless

Like Fields you can also get a specific method,
but it takes more information.
Calling all methods, report for
duty


To get a specific method you call








getMethod(String name, Class<?>… parameterTypes);

The name parameter is pretty straight forward,
but does Class<?>… mean?
This means you can pass any number of
Class<?> parameters after the name.
The Class<?> parameters you pass
reference the types of parameters the method
takes.
Calling all methods, report for
duty


For example, say we have this method:




If we were trying to get this specific method we
would have to call getMethod like this:




public int doSomething(String stuff, int times, int max){}

getMethod(“doSomething”, String.class, int.class,
int.class);

We are directly passing the types, and this is
because the reflection will use the method
“fingerprints” to track it down and return it to
us.
The Parts of the Class





Fields
Methods
Constructors
Miscellaneous
Building blocks


To get the constructos we have the methods:


getConstructors()
 Returns



getDeclaredConstructors()
 Returns

view



all public constructors for the class
all constructors for the class, regardless of

We can again get specific constructors with:


getConstructor(Class<?>… parameterTypes);
 Returns

the constructor that takes the given
parameters
The Parts of the Class





Fields
Methods
Constructors
Miscellaneous
The others


For this session we will only focus on variables
and methods, but there are a number of other
useful methods:


getEnclosingMethod()
 Gets



the method that declared an anonymous class

getName()
 Returns



the class name

newInstance()
 Creates

a new instance of the class
The Classes of Reflection





Field
Method
Constructor
????????????
The Field Class


Some useful methods:


get(Object obj)
 Gets the value of this field in the given object



getPrimitiveType(Object obj)



set(Object obj, Object value)
 Sets the value of this field in the given object, if possible



setPrimitiveType(Object obj, PrimitiveType value)



getType()
 Returns the type of this field



getName()
 Returns the name of this field
The Field Class






You may have noticed the two methods
getPrimitiveType(..) a nd setPrimitiveType(..)
Here PrimitiveType is replaced with a real
primative type, so if a field represents an int
you would say, getInt() or setInt().
This is done because primitive types are not
classes and so we need a special way to get
and set them
The Field Class




The first parameter to all of those methods
was Object obj
This parameter is a specific instance of the
class.






a constructed version of the class

Like I mentioned before the Field object
represents a generic version of a field for a
class, it holds no value, its just a blueprint as
to where it would be in the class.
To get a value we must provide a class that
has been constructed already.
The Field Class




Don’t forget we can have two types of fields,
static/non-static
If we want to get the value of a static field, we
can pass null as the Object obj parameter.
The Classes of Reflection





Field
Method
Constructor
????????????
The Method Class


Some useful methods


getName()

 Gets


getReturnType()

 Gets


the methods name
the type of variable returned by this method

getParameterTypes()

 Returns

an array of parameters in the order the
method takes them



invoke(Object obj, Object… args)

 Runs

this method on the given object, with
parameters.
The Method Class






The main method of this class that we will use
is invoke(Object obj, Object... params)
The first parameter is exactly like the Field
class methods, it is an instantiated class with
this method that we can invoke.
The second parameter means we can pass as
many parameters as necessary to call this
method, usually we will have to use the result
of getParameterTypes() in order to fill those in.
The Classes of Reflection





Field
Method
Constructor
????????????
The Constructor Class


Some useful methods


getParameterTypes()

 Returns

an array of parameter types that this
constructor takes



newInstance(Object… initargs)

 Creates

a new class that this constructor is from using
the given parameters as arguments.
The Constructor Class




Only two methods? Well yes, we only have an
hour to work with here! And the others are not
as interesting.
The method we are most concerned with is
newInstance(Object… initArgs)




This is similar to invoke(..) for methods except
we don’t pass an already instantiate object
because we are making a new one!
Like methods we will probably call
getParameterTypes() first.
Overview






Lets take a step back and look at all this
information
We can get a class blueprint and it’s a class of
type Class from java.lang.Class
For reflection we use classes like Field,
Method, and Constructor to reference pieces
of the class




These are generic versions and we must pass
them constructed versions (except for
constructors)
From each of these reflection classes we have
the ability to manipulate instances of classes.
Lets try it out!


Whats the fun in learning something without
trying it out?



Lets go!!
Lets try it out








So it turned out what we learned works pretty
well for everything with a public visibility.
But what about those private, protected, and
default views?
Java kept throwing an IllegalAccessException,
we just don’t have permissions to edit those.
Well not to worry we can get permission!
The Classes of Reflection





Field
Method
Constructor
????????????
The Classes of Reflection





Field
Method
Constructor
AccessibleObject!
The AccessibleObject


The accessible object is a superclass that
Field, Method, and Constructor extend





How convenient!

But what does it do?
It controls access to variables by checking the
accessibility of a field, method, or constructor
anytime you try to get, set, or invoke one.
The AccessibleObject


Some ve ry useful methods:


isAccessible()

 Tells

whether or not the object can be accessed
based on its view type
 A public field, method, or constructor will return true
 The other types will return false.


setAccessible(boolean flag)

 This

will override the accessibility setting to whatever
is passed in, true or false
Overriding Accessibility



So how can we use this?
Well suppose we have a Field object that
references a field in our class that was
declared like this:




private String secretMessage;

Well as we have seen we get an Exception,
but we can avoid it by overriding the
accessibility


theField.setAccessible(true);
Overriding Accessibility


Now before you start the triangle pyramid of
evil, note:





It is possible to prevent use of setAccessible()
You do this using a SecurityManager to prevent
access to variables
Stuarts CritterMain does this for tournaments.
Applying Reflection






Now that we have learned a little bit of
reflection and have some tools under our belt,
lets try it out.
You can download the ATM.class from the
course website
To run it you will need to go to the command
line, navigate to where you downloaded the
file and then type


java ATM
The Secure Financial
Corporation








An area where security is extremely important
is Banking
We trust that banks keep all of our
transactions secure and money safe
Lets suppose we were just hired to check the
security of Secure Financial Corporation’s new
Java powered ATM
We will need to use reflection to try and
leverage an attack against the machine.
The Secure Financial
Corporation






The company has decided it would be more
secure for the card to verify that an ATM is
valid by having cards that can execute
methods.
In particular every card must have a swipe
method that takes in an ATM object that the
card can use to validate is a real ATM.
The ATM has a method applyDecryption() that
the card must call to determine if the ATM has
the proper credentials (Security Session Tiein!)
The Secure Financial
Corporation






The card must pass an encrypted code to
applyDecryption() which will return a
decrypted code. The card can then use this
code to make sure the ATM has the
appropriate private keys. If it does then the
swipe method returns a Data object for ATM
with info.
That would be all well and good for a secure
system right?
That way cards don’t give out information to
bad systems!
The Secure Financial
Corporation






Well its nice in theory, but it gives us a built
ATM object!
And as we have just learned with Reflection,
we can get all the framework we want, but we
need an instantiated version of the class to do
real damage.
Lets see what we can do!
Arrays




If you wish to manipulate arrays with
Reflection you must use the
java.lang.reflect.Array class, you cannot use
the Field class
This is because Java does not handle Arrays
in the same way it handles Objects or
Primatives
Arrays


Useful Methods


get(Object array, int index)
 Gets




the value from the array at the given index

getPrimitiveType(Object array, int index)
set(Object array, int index, Object value)
 Sets

the value in the array at the index to the given
value



setPrimitiveType(Object array, int index,
PrimitiveType value)
Arrays




Just like the Field class, the Prim itive Ty p e is
replaced by an actual primitive type and you
must use this type of placement when
accessing a primitive array
But there are a couple more methods that are
unique to this class
Arrays


Unique Methods


getLength(Object array)
 Returns



the length of the given array

newInstance(Class<?> componentType, int…
dimensions)
 Creates

a new array of the given type and with the
given dimensions



newInstance(Class<?> componentType, int length)
 Creates

a new array of the given type and with the
given length
Critters


So the last example we will look at is using
Reflection to “win” Critters.
That’s all folks!






While there are many more things that make
up Reflection and even more things you can
do with Reflection, that is the extent of this
lecture.
I will post a secondary ATM that does not pass
an ATM object to the swipe method, can you
find the secret message and decode it?
Hint: You can get a copy of the instantiated
frames by calling JFrame.getInstances(), ATM
instantiates a Frame.
Ad

More Related Content

What's hot (20)

Java reflection
Java reflectionJava reflection
Java reflection
NexThoughts Technologies
 
Java Reflection Concept and Working
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and Working
Software Productivity Strategists, Inc
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
Sherihan Anver
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
bindur87
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
Sherihan Anver
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
TOPS Technologies
 
Java API, Exceptions and IO
Java API, Exceptions and IOJava API, Exceptions and IO
Java API, Exceptions and IO
Jussi Pohjolainen
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
Sunil Kumar Gunasekaran
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
Uzair Salman
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
Ye Win
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
CPD INDIA
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
Singsys Pte Ltd
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
Sherihan Anver
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Sagar Verma
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
Ganesh Samarthyam
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
Garuda Trainings
 
Introduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APIIntroduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection API
Niranjan Sarade
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
Lokesh Kakkar Mobile No. 814-614-5674
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
Terry Yoast
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
Sherihan Anver
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
bindur87
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
Sherihan Anver
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
TOPS Technologies
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
Sunil Kumar Gunasekaran
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
Uzair Salman
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
Ye Win
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
CPD INDIA
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Sagar Verma
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
Ganesh Samarthyam
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
Garuda Trainings
 
Introduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APIIntroduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection API
Niranjan Sarade
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
Terry Yoast
 

Similar to Reflection (20)

Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
ssuser8347a1
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
madhavi patil
 
classes-objects in oops java-201023154255.pptx
classes-objects in oops java-201023154255.pptxclasses-objects in oops java-201023154255.pptx
classes-objects in oops java-201023154255.pptx
janetvidyaanancys
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
sandy14234
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
talha ijaz
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
Unit i
Unit iUnit i
Unit i
snehaarao19
 
oops-1
oops-1oops-1
oops-1
snehaarao19
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
Hamid Ghorbani
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
Madishetty Prathibha
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
lykado0dles
 
Java basics
Java basicsJava basics
Java basics
Shivanshu Purwar
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
Gousalya Ramachandran
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
Sonu WIZIQ
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
Learn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & InheritanceLearn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & Inheritance
Eng Teong Cheah
 
Hemajava
HemajavaHemajava
Hemajava
SangeethaSasi1
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
Sean McElrath
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
madhavi patil
 
classes-objects in oops java-201023154255.pptx
classes-objects in oops java-201023154255.pptxclasses-objects in oops java-201023154255.pptx
classes-objects in oops java-201023154255.pptx
janetvidyaanancys
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
lykado0dles
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
Learn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & InheritanceLearn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & Inheritance
Eng Teong Cheah
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
Sean McElrath
 
Ad

More from Piyush Mittal (20)

Power mock
Power mockPower mock
Power mock
Piyush Mittal
 
Design pattern tutorial
Design pattern tutorialDesign pattern tutorial
Design pattern tutorial
Piyush Mittal
 
Gpu archi
Gpu archiGpu archi
Gpu archi
Piyush Mittal
 
Cuda Architecture
Cuda ArchitectureCuda Architecture
Cuda Architecture
Piyush Mittal
 
Intel open mp
Intel open mpIntel open mp
Intel open mp
Piyush Mittal
 
Intro to parallel computing
Intro to parallel computingIntro to parallel computing
Intro to parallel computing
Piyush Mittal
 
Cuda toolkit reference manual
Cuda toolkit reference manualCuda toolkit reference manual
Cuda toolkit reference manual
Piyush Mittal
 
Matrix multiplication using CUDA
Matrix multiplication using CUDAMatrix multiplication using CUDA
Matrix multiplication using CUDA
Piyush Mittal
 
Channel coding
Channel codingChannel coding
Channel coding
Piyush Mittal
 
Basics of Coding Theory
Basics of Coding TheoryBasics of Coding Theory
Basics of Coding Theory
Piyush Mittal
 
Java cheat sheet
Java cheat sheetJava cheat sheet
Java cheat sheet
Piyush Mittal
 
Google app engine cheat sheet
Google app engine cheat sheetGoogle app engine cheat sheet
Google app engine cheat sheet
Piyush Mittal
 
Git cheat sheet
Git cheat sheetGit cheat sheet
Git cheat sheet
Piyush Mittal
 
Css cheat sheet
Css cheat sheetCss cheat sheet
Css cheat sheet
Piyush Mittal
 
Ubuntu cheat sheet
Ubuntu cheat sheetUbuntu cheat sheet
Ubuntu cheat sheet
Piyush Mittal
 
Php cheat sheet
Php cheat sheetPhp cheat sheet
Php cheat sheet
Piyush Mittal
 
oracle 9i cheat sheet
oracle 9i cheat sheetoracle 9i cheat sheet
oracle 9i cheat sheet
Piyush Mittal
 
Open ssh cheet sheat
Open ssh cheet sheatOpen ssh cheet sheat
Open ssh cheet sheat
Piyush Mittal
 
Ad

Recently uploaded (20)

Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of ExchangesJignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah Innovator
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptxWebinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
MSP360
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
Does Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should KnowDoes Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should Know
Pornify CC
 
AI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdfAI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdf
Precisely
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of ExchangesJignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah Innovator
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptxWebinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
MSP360
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
Does Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should KnowDoes Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should Know
Pornify CC
 
AI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdfAI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdf
Precisely
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 

Reflection

  • 1. REFLECTION IN JAVA By: Zachary Cava
  • 2. What exactly is a class?  It’s a collection of different things, such as:     Fields Methods Constructors We define these different things with names, types, parameters, values, expressions, etc while programming, but in reflection all of this already exists.
  • 3. Programming vs Reflecting     We use reflection to manipulate things that already exist and, normally, are set. But unlike programming, we are not tied to specific names, types or views. We have the ability to dynamically change what things are, regardless of how they were written! More specifically, we are modifying objects at runtime.
  • 4. What do you mean Runtime?  Normally you program something like this:     Write/Modify the class, methods, etc Compile it Run it If you want to make any changes you have to recompile and rerun that class.
  • 5. What do you mean Runtime?  With reflection, we can manipulate a class without ever recompiling it:      Write/Modify the class, methods, etc Compile it Run it Modify the class here! It is important to note that another class is the one doing the modification.
  • 6. Uses of Reflection  Some common uses of reflection:  To load and use classes unknown at compile time, but have set methods.  Example:    The Critters assignment Test programs by forcing specific states By debuggers to inspect running programs Malicious things  Hacking
  • 7. Programming Reflection    To program with reflection, we must put on our meta-thinking caps. We are going to modify classes from classes with classes! To do this we have a great set of classes in the following package:  java.lang.reflect.*;
  • 8. Java.lang.reflect.* Some classes we will go over, (there are more): Method   Field   Describes a method for a class and gives access to it. Describes a field for a class, its type, name, etc. Constructor<T>  Provides information about constructors and the ability to execute a constructor and get a new class instance
  • 9. Java.lang.reflect.*  AccessibleObject   Describes the accessibility of an object, i.e. its view public, private, protected, default. Array  A special class created just for reflecting with Arrays, since Arrays are such odd objects in Java we must use this class to manipulate them.
  • 10. So where do we start?  To start manipulating a class we must first get a hold of that class’s “blueprint”.   There are two ways to do this, if the class is already loaded:   Class<? extends Object> theClass = ClassName.class; Or if we need to cause it to load:   Using the java.lang.Class class Class theClass = Class.forName(“class.package”); We won’t use this second one, its rather complex at times.  Example Package: “java.lang.String”
  • 11. So where do we start?     So now we have the definition of a class. This is like the blueprint to the entire thing, it lists where everything is and how to get to it. It is important to point out that this class has information that pertains to the structure of the class, not specific instance information, but hold that thought for a little later. For now lets look at how to get some information from the class
  • 12. The Parts of the Class     Fields Methods Constructors Miscellaneous
  • 13. Getting those sweet fields  There are two ways to get class fields:  getFields();  Returns an array of Field objects, specifically all the fields that are public for this class and its super classes.  getDeclaredFields();  Returns  an array of Field objects, regardless of view. Optionally if you know the field name:  getField(String name);  Returns a Field with the given name
  • 14. The Parts of the Class     Fields Methods Constructors Miscellaneous
  • 15. Calling all methods, report for duty  Like Fields there are two ways to get Methods  getMethods();  Returns all the public methods for this class and any it inherits from super classes.  getDeclaredMethods();  Returns of view.  all the methods for this class only regardless Like Fields you can also get a specific method, but it takes more information.
  • 16. Calling all methods, report for duty  To get a specific method you call     getMethod(String name, Class<?>… parameterTypes); The name parameter is pretty straight forward, but does Class<?>… mean? This means you can pass any number of Class<?> parameters after the name. The Class<?> parameters you pass reference the types of parameters the method takes.
  • 17. Calling all methods, report for duty  For example, say we have this method:   If we were trying to get this specific method we would have to call getMethod like this:   public int doSomething(String stuff, int times, int max){} getMethod(“doSomething”, String.class, int.class, int.class); We are directly passing the types, and this is because the reflection will use the method “fingerprints” to track it down and return it to us.
  • 18. The Parts of the Class     Fields Methods Constructors Miscellaneous
  • 19. Building blocks  To get the constructos we have the methods:  getConstructors()  Returns  getDeclaredConstructors()  Returns view  all public constructors for the class all constructors for the class, regardless of We can again get specific constructors with:  getConstructor(Class<?>… parameterTypes);  Returns the constructor that takes the given parameters
  • 20. The Parts of the Class     Fields Methods Constructors Miscellaneous
  • 21. The others  For this session we will only focus on variables and methods, but there are a number of other useful methods:  getEnclosingMethod()  Gets  the method that declared an anonymous class getName()  Returns  the class name newInstance()  Creates a new instance of the class
  • 22. The Classes of Reflection     Field Method Constructor ????????????
  • 23. The Field Class  Some useful methods:  get(Object obj)  Gets the value of this field in the given object  getPrimitiveType(Object obj)  set(Object obj, Object value)  Sets the value of this field in the given object, if possible  setPrimitiveType(Object obj, PrimitiveType value)  getType()  Returns the type of this field  getName()  Returns the name of this field
  • 24. The Field Class    You may have noticed the two methods getPrimitiveType(..) a nd setPrimitiveType(..) Here PrimitiveType is replaced with a real primative type, so if a field represents an int you would say, getInt() or setInt(). This is done because primitive types are not classes and so we need a special way to get and set them
  • 25. The Field Class   The first parameter to all of those methods was Object obj This parameter is a specific instance of the class.    a constructed version of the class Like I mentioned before the Field object represents a generic version of a field for a class, it holds no value, its just a blueprint as to where it would be in the class. To get a value we must provide a class that has been constructed already.
  • 26. The Field Class   Don’t forget we can have two types of fields, static/non-static If we want to get the value of a static field, we can pass null as the Object obj parameter.
  • 27. The Classes of Reflection     Field Method Constructor ????????????
  • 28. The Method Class  Some useful methods  getName()  Gets  getReturnType()  Gets  the methods name the type of variable returned by this method getParameterTypes()  Returns an array of parameters in the order the method takes them  invoke(Object obj, Object… args)  Runs this method on the given object, with parameters.
  • 29. The Method Class    The main method of this class that we will use is invoke(Object obj, Object... params) The first parameter is exactly like the Field class methods, it is an instantiated class with this method that we can invoke. The second parameter means we can pass as many parameters as necessary to call this method, usually we will have to use the result of getParameterTypes() in order to fill those in.
  • 30. The Classes of Reflection     Field Method Constructor ????????????
  • 31. The Constructor Class  Some useful methods  getParameterTypes()  Returns an array of parameter types that this constructor takes  newInstance(Object… initargs)  Creates a new class that this constructor is from using the given parameters as arguments.
  • 32. The Constructor Class   Only two methods? Well yes, we only have an hour to work with here! And the others are not as interesting. The method we are most concerned with is newInstance(Object… initArgs)   This is similar to invoke(..) for methods except we don’t pass an already instantiate object because we are making a new one! Like methods we will probably call getParameterTypes() first.
  • 33. Overview    Lets take a step back and look at all this information We can get a class blueprint and it’s a class of type Class from java.lang.Class For reflection we use classes like Field, Method, and Constructor to reference pieces of the class   These are generic versions and we must pass them constructed versions (except for constructors) From each of these reflection classes we have the ability to manipulate instances of classes.
  • 34. Lets try it out!  Whats the fun in learning something without trying it out?  Lets go!!
  • 35. Lets try it out     So it turned out what we learned works pretty well for everything with a public visibility. But what about those private, protected, and default views? Java kept throwing an IllegalAccessException, we just don’t have permissions to edit those. Well not to worry we can get permission!
  • 36. The Classes of Reflection     Field Method Constructor ????????????
  • 37. The Classes of Reflection     Field Method Constructor AccessibleObject!
  • 38. The AccessibleObject  The accessible object is a superclass that Field, Method, and Constructor extend    How convenient! But what does it do? It controls access to variables by checking the accessibility of a field, method, or constructor anytime you try to get, set, or invoke one.
  • 39. The AccessibleObject  Some ve ry useful methods:  isAccessible()  Tells whether or not the object can be accessed based on its view type  A public field, method, or constructor will return true  The other types will return false.  setAccessible(boolean flag)  This will override the accessibility setting to whatever is passed in, true or false
  • 40. Overriding Accessibility   So how can we use this? Well suppose we have a Field object that references a field in our class that was declared like this:   private String secretMessage; Well as we have seen we get an Exception, but we can avoid it by overriding the accessibility  theField.setAccessible(true);
  • 41. Overriding Accessibility  Now before you start the triangle pyramid of evil, note:    It is possible to prevent use of setAccessible() You do this using a SecurityManager to prevent access to variables Stuarts CritterMain does this for tournaments.
  • 42. Applying Reflection    Now that we have learned a little bit of reflection and have some tools under our belt, lets try it out. You can download the ATM.class from the course website To run it you will need to go to the command line, navigate to where you downloaded the file and then type  java ATM
  • 43. The Secure Financial Corporation     An area where security is extremely important is Banking We trust that banks keep all of our transactions secure and money safe Lets suppose we were just hired to check the security of Secure Financial Corporation’s new Java powered ATM We will need to use reflection to try and leverage an attack against the machine.
  • 44. The Secure Financial Corporation    The company has decided it would be more secure for the card to verify that an ATM is valid by having cards that can execute methods. In particular every card must have a swipe method that takes in an ATM object that the card can use to validate is a real ATM. The ATM has a method applyDecryption() that the card must call to determine if the ATM has the proper credentials (Security Session Tiein!)
  • 45. The Secure Financial Corporation    The card must pass an encrypted code to applyDecryption() which will return a decrypted code. The card can then use this code to make sure the ATM has the appropriate private keys. If it does then the swipe method returns a Data object for ATM with info. That would be all well and good for a secure system right? That way cards don’t give out information to bad systems!
  • 46. The Secure Financial Corporation    Well its nice in theory, but it gives us a built ATM object! And as we have just learned with Reflection, we can get all the framework we want, but we need an instantiated version of the class to do real damage. Lets see what we can do!
  • 47. Arrays   If you wish to manipulate arrays with Reflection you must use the java.lang.reflect.Array class, you cannot use the Field class This is because Java does not handle Arrays in the same way it handles Objects or Primatives
  • 48. Arrays  Useful Methods  get(Object array, int index)  Gets   the value from the array at the given index getPrimitiveType(Object array, int index) set(Object array, int index, Object value)  Sets the value in the array at the index to the given value  setPrimitiveType(Object array, int index, PrimitiveType value)
  • 49. Arrays   Just like the Field class, the Prim itive Ty p e is replaced by an actual primitive type and you must use this type of placement when accessing a primitive array But there are a couple more methods that are unique to this class
  • 50. Arrays  Unique Methods  getLength(Object array)  Returns  the length of the given array newInstance(Class<?> componentType, int… dimensions)  Creates a new array of the given type and with the given dimensions  newInstance(Class<?> componentType, int length)  Creates a new array of the given type and with the given length
  • 51. Critters  So the last example we will look at is using Reflection to “win” Critters.
  • 52. That’s all folks!    While there are many more things that make up Reflection and even more things you can do with Reflection, that is the extent of this lecture. I will post a secondary ATM that does not pass an ATM object to the swipe method, can you find the secret message and decode it? Hint: You can get a copy of the instantiated frames by calling JFrame.getInstances(), ATM instantiates a Frame.
  翻译: