SlideShare uma empresa Scribd logo
1 de 14
Baixar para ler offline
Java course - IAG0040




                 Networking,
             Reflection & Logging



Anton Keks                             2011
Networking
 ●   Java provides cross-platform networking facilities
 ●
     java.net and javax.net packages contain many useful classes
 ●   API is generally protocol independent, but implementation supports
     mostly Internet transport protocols, e.g. TCP and UDP
 ●   java.net.InetAddress represents an IP address (immutable)
      –   Inet4Address represents 32-bit IPv4 addresses (4 billions)
      –   Inet6Address represents 128-bit IPv6 addresses (3.4 x 10 38)
      –   It is able to detect address types, provides naming services, and
          various other checks and conversions
      –   Create using InetAddress.getByAddress(...), getByName(...)
          or getLocalHost()
      –   Many getXXX() and isXXX() methods provided
Java course – IAG0040                                                     Lecture 9
Anton Keks                                                                  Slide 2
Sockets
 ●   Sockets are used as endpoints in network communication
 ●
     java.net.InetSocketAddress represents an address-port pair
 ●   There are several types of sockets in Java
      –   Socket and ServerSocket – connection-oriented streaming reliable client
          and server sockets (TCP)
      –   SSLSocket and SSLServerSocket – client and server sockets for secure
          encrypted communication (TCP via SSL)
      –   DatagramSocket – packet-oriented unreliable socket for both sending and
          receiving data (UDP), can be used for both unicasting and broadcasting
      –   MulticastSocket – datagram socket with multicasting support
 ●   Socket implementations depend on respective factory classes. Direct
     usage uses the default socket factory for the given socket type.

Java course – IAG0040                                                   Lecture 9
Anton Keks                                                                Slide 3
Networking Exceptions
 ●
     Most networking exceptions extend
     SocketException
 ●   SocketException extends IOException, showing
     that networking is highly related to all other
     more generic I/O classes




Java course – IAG0040                         Lecture 9
Anton Keks                                      Slide 4
Streaming Sockets
 ●   Socket and ServerSocket can be used for streaming
 ●   Underlying Socket implementations are provided by
     SocketImplFactory classes by the means of SocketImpl classes.
     Default implementation is plain TCP.
 ●   getInputStream() and getOutputStream() are used for
     obtaining the streams, both can be used simultaneously
 ●   Various socket options may be set using provided set methods
 ●   There are many informative is/get methods provided
 ●   Stream sockets must be closed using the close() method
      –   it closes both streams automatically as well


Java course – IAG0040                                      Lecture 9
Anton Keks                                                   Slide 5
Datagram Sockets
 ●
     DatagramSocket is used for sending and receiving of
     DatagramPackets; receiving is actually 'listening'
 ●
     Connection-less, no streams provided
 ●   connect() and disconnect() is used for
     selecting/resetting the remote party's address and port
 ●
     Special addresses can be used for sending/receiving of
     broadcast packets, e.g. 192.168.0.255
 ●
     MulticastSocket can be used for joining/leaving multicast
     groups of DatagramSockets. Multicast groups have special
     addresses.

Java course – IAG0040                                     Lecture 9
Anton Keks                                                  Slide 6
URL and URLConnection
●
    Java also provides higher-level networking APIs than Sockets
●
    URI and URL classes provide construction and parsing of the
    respective Strings (all URLs are URIs, however)
     –   URI is a newer class and provides encoding/decoding of
         escaped symbols, like %20
     –   Conversions back and forth are possible using toURI()
         and toURL() methods
●
    URLConnection provides API for reading/writing of the
    resources referenced by URLs
●   url.openConnection() returns a subclass of
    URLConnection, according to the registered protocol-specific
    URLStreamHandler
                                                             Lecture 9
                                                               Slide 7
URL and URLConnection (cont)
●   Obtained URLConnection can be used for setting various
    parameters (headers)
    –   Actual connection is opened using the connect() method
    –   Both getInputStream() and getOutputStream() are
        provided
    –   getContent() returns an Object according to the MIME
        type of the resource, which ContentHandler is provided by
        the ContentHandlerFactory
●   url.openStream() is a shortcut if you need to just retrieve
    the data without any extra features
●
    Proxy/ProxySelector can be used for proxying of traffic
                                                         Lecture 9
                                                           Slide 8
Networking Task
●
    Implement the FileDownloader (eg using existing
    DataCopier implementation)
●
    Try your code with various Input and Output streams
        –   Files, Sockets, URLs
●
    Create FileSender and FileReceiveServer classes. Reuse
    already written code to send file content over the socket
    and save content to another file on the server end




                                                       Lecture 9
                                                         Slide 9
Reflection API
 ●   The reflection API represents, or reflects, the
     classes, interfaces, and objects in the current
     JVM
     –   It is possible to dynamically collect information about
         all aspects of compiled entities, even access private
         fields
 ●   Reflection API is in java.lang and
     java.lang.reflect packages
 ●   Note: Reflection API is also full of generics
     (for convenience)

Java course – IAG0040                                      Lecture 9
Anton Keks                                                  Slide 10
Reflection API usage
 ●
     Where is it appropriate to use it?
     –   various plugins and extensions: load classes by
         name, etc
     –   JUnit uses reflection for finding test methods
         either by name or annotations
     –   Many other famous frameworks use reflection, e.g.
         Hibernate, Spring, Struts, Log4J, JUnit, etc
 ●
     Caution: use reflection only when it is absolutely
     necessary!

Java course – IAG0040                                     Lecture 9
Anton Keks                                                 Slide 11
Examining Classes
●
    Class objects reflect Java classes
     –   Every Object provides the getClass() method
     –   Various methods of Class return instances of Field, Method, Constructor,
         Package, etc
          ●   methods in plural return arrays, e.g. getFields(), getMethods()
          ●   methods in singular return single instances according to search
              criteria, e.g. getField(...), getMethod(...)
     –   Class can also represent primitive types, interfaces, arrays, enums and
         annotations
●   Java supports Class literals, e.g. String.class, int.class
●   Class.forName() is used for loading classes dynamically
●   Modifiers: Modifier.isPublic(clazz.getModifiers())
●   getSuperclass() returns the super class
Java course – IAG0040                                                      Lecture 9
Anton Keks                                                                  Slide 12
Instantiating Classes
 ●   clazz.newInstance() works for default constructors
 ●   Otherwise getConstructor(...) will provide a Constructor
     instance, which has its own newInstance(...)
 ●   Singular Constructor and Method finding methods take Class
     instances for matching of parameters:
     –   Constructor c = clazz.getConstructor(int.class,
         Date.class);
 ●   Then, creation (newInstance) or invocation (invoke) takes
     the real parameter values:
     –   Object o = c.newInstance(3, new Date());
     –   Primitive values are autoboxed to their wrapper classes

Java course – IAG0040                                              Lecture 9
Anton Keks                                                          Slide 13
Reflection Tips
 ●   Array class provides additional options for dynamic manipulation of arrays
 ●   Even this works: byte[].class
 ●   Retrieve class name of any object: object.getClass().getName()
 ●   Don't hardcode class names in Strings:
     MegaClass.class.getName() or .getSimpleName() is better
 ●   Accessing private fields:
      –   boolean wasAccessible = field.getAccessible();
          field.setAccessible(true);
          Object value = field.get(instance);
          field.setAccessible(wasAccessible);
 ●   Dynamic proxies allow to wrap objects and intercept method calls on them
     defined in their implemented interfaces:
      –   Object wrapped = Proxy.newProxyInstance(
              o.getClass().getClassLoader(), o.getClass().getInterfaces(),
              new InvocationHandler() { ... });
Java course – IAG0040                                                  Lecture 9
Anton Keks                                                              Slide 14

Mais conteúdo relacionado

Mais procurados

2 second lesson- attributes
2 second lesson- attributes2 second lesson- attributes
2 second lesson- attributes
Mohammad Alyan
 

Mais procurados (19)

Serialization in .NET
Serialization in .NETSerialization in .NET
Serialization in .NET
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
2 second lesson- attributes
2 second lesson- attributes2 second lesson- attributes
2 second lesson- attributes
 
Core java1
Core java1Core java1
Core java1
 
Session 10 - OOP with Java - Abstract Classes and Interfaces
Session 10 - OOP with Java - Abstract Classes and InterfacesSession 10 - OOP with Java - Abstract Classes and Interfaces
Session 10 - OOP with Java - Abstract Classes and Interfaces
 
28 networking
28  networking28  networking
28 networking
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
 
Just entity framework
Just entity frameworkJust entity framework
Just entity framework
 
Arrays in Java
Arrays in Java Arrays in Java
Arrays in Java
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Java - Sockets
Java - SocketsJava - Sockets
Java - Sockets
 
Basics of building a blackfin application
Basics of building a blackfin applicationBasics of building a blackfin application
Basics of building a blackfin application
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
 
Scala eXchange opening
Scala eXchange openingScala eXchange opening
Scala eXchange opening
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
 
04 sorting
04 sorting04 sorting
04 sorting
 
04 Java Language And OOP Part IV
04 Java Language And OOP Part IV04 Java Language And OOP Part IV
04 Java Language And OOP Part IV
 
Java
Java Java
Java
 
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
 

Destaque

Destaque (20)

Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
 
Java Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & EncodingsJava Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & Encodings
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, Hibernate
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
 
java packages
java packagesjava packages
java packages
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to Agile
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: Introduction
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
 
Java package
Java packageJava package
Java package
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 

Semelhante a Java Course 9: Networking and Reflection

04 android
04 android04 android
04 android
guru472
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdf
AdilAijaz3
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
koji lin
 

Semelhante a Java Course 9: Networking and Reflection (20)

Lecture10
Lecture10Lecture10
Lecture10
 
Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11
 
Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - Threads
 
Writing Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason LeeWriting Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason Lee
 
Java adv
Java advJava adv
Java adv
 
Java seminar.pptx
Java seminar.pptxJava seminar.pptx
Java seminar.pptx
 
04 android
04 android04 android
04 android
 
Spock
SpockSpock
Spock
 
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
 
Unit3 packages & interfaces
Unit3 packages & interfacesUnit3 packages & interfaces
Unit3 packages & interfaces
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdf
 
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
 
Dynamic Proxy by Java
Dynamic Proxy by JavaDynamic Proxy by Java
Dynamic Proxy by Java
 
Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+Concurrency
 
Java 7: Quo vadis?
Java 7: Quo vadis?Java 7: Quo vadis?
Java 7: Quo vadis?
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
 
Java quick reference
Java quick referenceJava quick reference
Java quick reference
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Último (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

Java Course 9: Networking and Reflection

  • 1. Java course - IAG0040 Networking, Reflection & Logging Anton Keks 2011
  • 2. Networking ● Java provides cross-platform networking facilities ● java.net and javax.net packages contain many useful classes ● API is generally protocol independent, but implementation supports mostly Internet transport protocols, e.g. TCP and UDP ● java.net.InetAddress represents an IP address (immutable) – Inet4Address represents 32-bit IPv4 addresses (4 billions) – Inet6Address represents 128-bit IPv6 addresses (3.4 x 10 38) – It is able to detect address types, provides naming services, and various other checks and conversions – Create using InetAddress.getByAddress(...), getByName(...) or getLocalHost() – Many getXXX() and isXXX() methods provided Java course – IAG0040 Lecture 9 Anton Keks Slide 2
  • 3. Sockets ● Sockets are used as endpoints in network communication ● java.net.InetSocketAddress represents an address-port pair ● There are several types of sockets in Java – Socket and ServerSocket – connection-oriented streaming reliable client and server sockets (TCP) – SSLSocket and SSLServerSocket – client and server sockets for secure encrypted communication (TCP via SSL) – DatagramSocket – packet-oriented unreliable socket for both sending and receiving data (UDP), can be used for both unicasting and broadcasting – MulticastSocket – datagram socket with multicasting support ● Socket implementations depend on respective factory classes. Direct usage uses the default socket factory for the given socket type. Java course – IAG0040 Lecture 9 Anton Keks Slide 3
  • 4. Networking Exceptions ● Most networking exceptions extend SocketException ● SocketException extends IOException, showing that networking is highly related to all other more generic I/O classes Java course – IAG0040 Lecture 9 Anton Keks Slide 4
  • 5. Streaming Sockets ● Socket and ServerSocket can be used for streaming ● Underlying Socket implementations are provided by SocketImplFactory classes by the means of SocketImpl classes. Default implementation is plain TCP. ● getInputStream() and getOutputStream() are used for obtaining the streams, both can be used simultaneously ● Various socket options may be set using provided set methods ● There are many informative is/get methods provided ● Stream sockets must be closed using the close() method – it closes both streams automatically as well Java course – IAG0040 Lecture 9 Anton Keks Slide 5
  • 6. Datagram Sockets ● DatagramSocket is used for sending and receiving of DatagramPackets; receiving is actually 'listening' ● Connection-less, no streams provided ● connect() and disconnect() is used for selecting/resetting the remote party's address and port ● Special addresses can be used for sending/receiving of broadcast packets, e.g. 192.168.0.255 ● MulticastSocket can be used for joining/leaving multicast groups of DatagramSockets. Multicast groups have special addresses. Java course – IAG0040 Lecture 9 Anton Keks Slide 6
  • 7. URL and URLConnection ● Java also provides higher-level networking APIs than Sockets ● URI and URL classes provide construction and parsing of the respective Strings (all URLs are URIs, however) – URI is a newer class and provides encoding/decoding of escaped symbols, like %20 – Conversions back and forth are possible using toURI() and toURL() methods ● URLConnection provides API for reading/writing of the resources referenced by URLs ● url.openConnection() returns a subclass of URLConnection, according to the registered protocol-specific URLStreamHandler Lecture 9 Slide 7
  • 8. URL and URLConnection (cont) ● Obtained URLConnection can be used for setting various parameters (headers) – Actual connection is opened using the connect() method – Both getInputStream() and getOutputStream() are provided – getContent() returns an Object according to the MIME type of the resource, which ContentHandler is provided by the ContentHandlerFactory ● url.openStream() is a shortcut if you need to just retrieve the data without any extra features ● Proxy/ProxySelector can be used for proxying of traffic Lecture 9 Slide 8
  • 9. Networking Task ● Implement the FileDownloader (eg using existing DataCopier implementation) ● Try your code with various Input and Output streams – Files, Sockets, URLs ● Create FileSender and FileReceiveServer classes. Reuse already written code to send file content over the socket and save content to another file on the server end Lecture 9 Slide 9
  • 10. Reflection API ● The reflection API represents, or reflects, the classes, interfaces, and objects in the current JVM – It is possible to dynamically collect information about all aspects of compiled entities, even access private fields ● Reflection API is in java.lang and java.lang.reflect packages ● Note: Reflection API is also full of generics (for convenience) Java course – IAG0040 Lecture 9 Anton Keks Slide 10
  • 11. Reflection API usage ● Where is it appropriate to use it? – various plugins and extensions: load classes by name, etc – JUnit uses reflection for finding test methods either by name or annotations – Many other famous frameworks use reflection, e.g. Hibernate, Spring, Struts, Log4J, JUnit, etc ● Caution: use reflection only when it is absolutely necessary! Java course – IAG0040 Lecture 9 Anton Keks Slide 11
  • 12. Examining Classes ● Class objects reflect Java classes – Every Object provides the getClass() method – Various methods of Class return instances of Field, Method, Constructor, Package, etc ● methods in plural return arrays, e.g. getFields(), getMethods() ● methods in singular return single instances according to search criteria, e.g. getField(...), getMethod(...) – Class can also represent primitive types, interfaces, arrays, enums and annotations ● Java supports Class literals, e.g. String.class, int.class ● Class.forName() is used for loading classes dynamically ● Modifiers: Modifier.isPublic(clazz.getModifiers()) ● getSuperclass() returns the super class Java course – IAG0040 Lecture 9 Anton Keks Slide 12
  • 13. Instantiating Classes ● clazz.newInstance() works for default constructors ● Otherwise getConstructor(...) will provide a Constructor instance, which has its own newInstance(...) ● Singular Constructor and Method finding methods take Class instances for matching of parameters: – Constructor c = clazz.getConstructor(int.class, Date.class); ● Then, creation (newInstance) or invocation (invoke) takes the real parameter values: – Object o = c.newInstance(3, new Date()); – Primitive values are autoboxed to their wrapper classes Java course – IAG0040 Lecture 9 Anton Keks Slide 13
  • 14. Reflection Tips ● Array class provides additional options for dynamic manipulation of arrays ● Even this works: byte[].class ● Retrieve class name of any object: object.getClass().getName() ● Don't hardcode class names in Strings: MegaClass.class.getName() or .getSimpleName() is better ● Accessing private fields: – boolean wasAccessible = field.getAccessible(); field.setAccessible(true); Object value = field.get(instance); field.setAccessible(wasAccessible); ● Dynamic proxies allow to wrap objects and intercept method calls on them defined in their implemented interfaces: – Object wrapped = Proxy.newProxyInstance( o.getClass().getClassLoader(), o.getClass().getInterfaces(), new InvocationHandler() { ... }); Java course – IAG0040 Lecture 9 Anton Keks Slide 14