#Java #SpringBoot #SpringWeb #RestTemplate 𝗛𝗼𝘄 𝘁𝗼 𝗺𝗮𝗸𝗲 𝗥𝗲𝘀𝘁𝗧𝗲𝗺𝗽𝗹𝗮𝘁𝗲 𝗿𝗲𝘁𝘂𝗿𝗻 𝗮 𝗟𝗶𝘀𝘁<𝗬𝗼𝘂𝗿𝗧𝘆𝗽𝗲> When you request a single object with RestTemplate, mapping is straightforward. Returning a List<T> is trickier because of Java’s type erasure at runtime List<Foo> looks like List. Spring’s RestTemplate needs help to know the concrete element type so Jackson (or another HttpMessageConverter) can deserialize JSON into List<YourType>. 𝗪𝗵𝘆 𝗶𝘁’𝘀 𝘁𝗿𝗶𝗰𝗸𝘆 Java generics are erased at runtime. A List<Student> and a List<Object> are both just List to the JVM. RestTemplate and Jackson therefore cannot automatically deduce the T in List<T>. You must provide explicit type information when you want a typed list response. 𝗥𝗲𝗰𝗼𝗺𝗺𝗲𝗻𝗱𝗲𝗱 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: exchange() + ParameterizedTypeReference This is the most common, type-safe approach: ResponseEntity<List<Enrollment>> response = restTemplate.exchange( "http://localhost:8082/api/v1/enrollments/{studentId}", HttpMethod.GET, null, // or new HttpEntity<>(headers) new ParameterizedTypeReference<List<Enrollment>>() {}, studentId ); List<Enrollment> enrollments = response.getBody(); where restTemplate is a bean in a configuration class: @Bean public RestTemplate restTemplate() { return new RestTemplate(); } 𝗡𝗼𝘁𝗲𝘀: - ParameterizedTypeReference<List<Enrollment>>() {} is an anonymous subclass that preserves the generic type info at runtime for Spring to use. - You can pass headers via HttpEntity<T> if you need Accept or authorization headers. 𝗧𝗵𝗲𝗿𝗲 𝗶𝘀 𝗮𝗻𝗼𝘁𝗵𝗲𝗿 𝘀𝗼𝗹𝘂𝘁𝗶𝗼𝗻: Request an array YourType[] (getForObject(..., YourType[].class)) and convert with Arrays.asList(...)
Aymen FARHANI’s Post
More Relevant Posts
-
⚙️ Java ClassLoader — How Java Loads Your Classes Before main() Even Runs 🧠 Ever wondered what happens before your public static void main() starts executing? Spoiler: A LOT. The JVM has a behind-the-scenes hero called the ClassLoader — and without it, your entire Java program wouldn’t even start. Let’s break it down 👇 --- 🔹 1️⃣ The Three Core ClassLoaders When you run your app, Java loads classes into memory using this hierarchy: ✔ Bootstrap ClassLoader Loads core Java classes (java.lang, java.util, etc.). Runs in native code — you can’t override it. ✔ Extension (Platform) ClassLoader Loads JARs from the JVM’s lib/ext directory. ✔ Application (System) ClassLoader Loads your classes from the classpath (target/classes, external libs, etc.). Your code runs because this loader finds and loads your .class files 📦 --- 🔹 2️⃣ The Class Loading Process Class loading happens in three phases: 1️⃣ Loading: Find .class → read bytecode → bring it into memory. 2️⃣ Linking: Verify bytecode ✔ Prepare static variables ✔ Resolve references ✔ 3️⃣ Initialization: Run static blocks and assign static variables. Only after this your class is ready. Example 👇 static { System.out.println("Class Loaded!"); } This runs before main(). --- 🔹 3️⃣ Why Developers Should Care Understanding ClassLoaders helps you: Debug “ClassNotFoundException” & “NoClassDefFoundError” better Work with frameworks like Spring (which use custom classloaders) Build plugins or modular architectures Understand how Java isolates and manages classes internally This is deep JVM knowledge — and mastering it makes you a stronger engineer 💪 #Java #JVM #ClassLoader #BackendDevelopment #JavaInternals #SoftwareEngineering #CleanCode #JavaDeveloper
To view or add a comment, sign in
-
🔹 collect(Collector<T> coll) in Java Stream API collect() is a predefined terminal operation of the Stream interface. It’s used to gather the results of intermediate operations and convert them into a desired Collection or Map type. It accepts an implementation of the Collector<T> interface as a parameter. The Collectors class provides several ready-to-use methods 👇 🧩 Common Collectors in Java 1️⃣ toList() – Converts stream elements into a List (✅ duplicates allowed). List<Integer> list = stream.collect(Collectors.toList()); 2️⃣ toSet() – Converts stream elements into a Set (🚫 duplicates not allowed). Set<Integer> set = stream.collect(Collectors.toSet()); 3️⃣ toMap() – Converts elements into a Map. Internally uses HashMap, so the order is unpredictable. It accepts two functions → keyMapper and valueMapper. Map<Integer, String> map = list.stream() .collect(Collectors.toMap(String::length, s -> s)); 4️⃣ joining(CharSequence delimiter) – Joins stream elements into a single String. String names = Stream.of("Java", "Spring", "Hibernate") .collect(Collectors.joining(", ")); 5️⃣ groupingBy(Function<T, R>) – Groups elements based on a specific criterion. Map<Integer, List<String>> grouped = Stream.of("one", "two", "three", "four") .collect(Collectors.groupingBy(String::length)); 6️⃣ partitioningBy(Predicate<T>) – Splits elements into two groups: true and false. Map<Boolean, List<Integer>> partitioned = Stream.of(5, 10, 15, 20) .collect(Collectors.partitioningBy(n -> n > 10)); 💡 In short: collect() = “Collect results of Stream processing into a Collection or Map efficiently.” #Java #StreamAPI #Collectors #Java8 #Programming
To view or add a comment, sign in
-
🔖 Annotations in Java: The Metadata That Powers Modern Frameworks Behind every clean, modern Java framework lies the silent power of annotations the metadata that tells the compiler and runtime what to do. Here’s what you’ll discover in this guide: ▪️What Annotations Really Are → Metadata that configures, documents, and automates behavior without altering logic. ▪️Built-in Annotations → @Override, @Deprecated, and @SuppressWarnings — your must-know compiler helpers. ▪️Custom Annotations → Create your own @interface annotations for validation, logging, or automation. ▪️Retention Policies → Learn where annotations live — at source, bytecode, or runtime. ▪️Target Types → Control where annotations can be applied — class, method, field, or parameter. ▪️Real-World Use Cases → See how Spring, Hibernate, and JUnit use annotations like @Autowired, @Entity, and @Test to simplify configuration. ▪️Interview Q&A → Understand retention, target, and runtime use — topics every Java interview covers. 📌 Like, Save & Follow CRIO.DO for more Java deep-dives made simple. 💻 Learn Java by Building Real Frameworks At CRIO.DO, you’ll master advanced Java concepts from annotations to dependency injection by actually building backend systems and Spring-based projects. 🚀 Book your FREE trial today- https://lnkd.in/geb_GYW2 and start coding like a pro! #Java #Annotations #CrioDo #LearnJava #SoftwareDevelopment #SpringFramework #Hibernate #JUnit #BackendEngineering #CodeSmart
To view or add a comment, sign in
-
💡 The Truth About Java Pass-by-Value — Why Objects Don’t Behave as You Think 🧠 Here’s a classic Java debate: > “Does Java pass objects by reference or by value?” Most developers confidently say “by reference”… ❌ But that’s actually wrong. Let’s settle this once and for all 👇 --- 🔹 1️⃣ Java is ALWAYS Pass-by-Value But wait — what does that really mean? When you call a method, Java passes a copy of the value — and when the value is a reference to an object, it copies the reference, not the actual object. So yes, objects feel like they’re passed by reference, but it’s actually the reference itself being passed by value. Mind twist? Let’s see an example 👇 --- 🔹 2️⃣ Example void changeName(User user) { user.setName("Tushar"); } User u = new User("Alex"); changeName(u); System.out.println(u.getName()); // "Tushar" ✅ Here, the reference to u is copied, so both point to the same object — any changes reflect. --- But if you reassign the reference inside the method 👇 void changeUser(User user) { user = new User("Rahul"); } User u = new User("Alex"); changeUser(u); System.out.println(u.getName()); // Still "Alex" ❌ Because that reassignment only affects the local copy of the reference, not the original one in the caller method. --- 🔹 3️⃣ The Key Takeaway 🧠 Java always passes by value, even for objects. It’s just that — Primitives pass their value directly Objects pass a copy of the reference So you can change the object’s state inside a method, but not which object the caller’s variable points to. --- 💬 Your Turn: Did you used to think Java passed objects by reference? 😅 👇 Drop your “aha!” moment in the comments — let’s see how many devs learned this the hard way! #Java #CleanCode #OOP #SoftwareEngineering #BackendDevelopment #JVM #JavaDeveloper #CodeTips
To view or add a comment, sign in
-
Strings:- String comparison techniques in Java 1️⃣ == Operator Definition: Compares the memory references of two strings — checks if both variables point to the same object in memory, not the content. 2️⃣ equals() Method Definition: Compares the actual content (value) of two strings — returns true if both strings contain the same sequence of characters (case-sensitive). 3️⃣ equalsIgnoreCase() Method Definition: Compares the content of two strings while ignoring case differences (uppercase or lowercase letters). 4️⃣ compareTo() Method Definition: Compares two strings lexicographically (alphabetical order) and returns: 0 → if both strings are equal Positive value → if the first string is greater Negative value → if the first string is smaller 5️⃣ compareToIgnoreCase() Method Definition: Works like compareTo() but ignores case differences during comparison. 6️⃣ contentEquals() Method Definition: Checks if a string has the exact same sequence of characters as another String or StringBuffer. 7️⃣ matches() Method Definition: Tests whether a string matches a given regular expression pattern, often used for validation (like checking email format). String Memory Handling: Strings created using literals go to the String Constant Pool (SCP). Strings created using new keyword are stored in heap memory. This helps Java save memory by reusing identical strings from the SCP. Real-World Example: Imagine you’re building an e-commerce website — Strings are used for: Product names (String productName = "Smartphone";) Order IDs (String orderId = "ORD1234";) Customer names, addresses, and messages Efficient use of StringBuilder can optimize the performance of your backend services while generating dynamic data (like invoices or receipts). Takeaway: Strings are the backbone of data handling in Java — They represent text, manage input/output, and connect nearly every part of an application. Choose wisely: String → when immutability is needed StringBuilder → for fast, single-threaded modification StringBuffer → for thread-safe operations #Java #CoreJava #StringInJava #JavaProgramming #LearnJava #CodingJourney #TechLearning #SoftwareDevelopment
To view or add a comment, sign in
-
In the world of Java and working with the Spring framework, encountering a “bean initialization problem” is inevitable. Let's take a general look at this type of error. In a Java application, especially one using Spring Framework or similar dependency injection (DI) containers, the “bean initialization problem” usually refers to issues that occur when a Spring bean (i.e., a managed object) fails to initialize properly. Common Root Causes of Bean Initialization Problems: ✔️ Missing dependency ✔️ Circular dependency ✔️ Constructor error ✔️ Wrong configuration ✔️ Environment issues ✔️ Proxy / AOP issues But the important point is who is actually responsible for finding this type of error. JVM or Spring ? Which one on which side? The JVM itself doesn’t know anything about beans — it only loads Java classes into memory (via the classloader). The Spring container (e.g. ApplicationContext) builds on top of the JVM to manage beans — it decides what to instantiate and how. So: The JVM loads your classes; Spring analyzes those classes for bean definitions and manages them. When I built my application — which was working perfectly on my local environment — and tried to deploy it to the production environment, I encountered a "bean initialization error". I started thinking about where to begin debugging and exactly where in my code the error was coming from, especially since the system log only pointed to a class that I hadn’t made any changes to. That’s why I decided to review the steps that Spring follows to locate and initialize a bean. Classpath scanning: Spring scans for annotated classes (@Component, @Service, @Configuration, etc.) based on @ComponentScan. Bean definition creation: For each found class, Spring creates a BeanDefinition — a metadata object describing how to create that bean. Dependency resolution: Before creating the bean, Spring resolves all constructor and field dependencies. Bean instantiation: Spring uses reflection to call the constructor or factory method. Initialization callbacks: Spring calls lifecycle hooks like @PostConstruct or afterPropertiesSet(). If any step fails, Spring throws a BeanCreationException or BeanInitializationException. If any interesting points come to your mind, I’d appreciate it if you shared them with me. 🙂 #JavaDevelopment #SpringFramework #coding #Java #SpringBoot
To view or add a comment, sign in
-
* Exception Handling in Java: In Java, Exception Handling helps us deal with unexpected events (errors) gracefully without crashing the program * What is an Exception? An exception is an event that disrupts the normal flow of execution. It can occur due to runtime errors like: Division by zero File not found Null reference access ⚙️ Key Keywords: 1)try → Block of code to test for errors. 2)catch → Handles the exception. 3)finally → Executes code whether exception occurs or not. 4)throw → Used to throw an exception manually. 5)throws → Declares exceptions in method signature. 🧩 Example: public class ExceptionExample { public static void main(String[] args) { try { int a = 10 / 0; // ArithmeticException } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); } finally { System.out.println("Execution complete!"); } } } ✅ Output: Cannot divide by zero! Execution complete! 📘 Types of Exceptions: 1️⃣ Checked Exceptions – Checked at compile time (e.g., IOException, SQLException). 2️⃣ Unchecked Exceptions – Occur at runtime (e.g., NullPointerException, ArithmeticException). 3️⃣ Errors – Serious issues (e.g., OutOfMemoryError) – not handled by application code. 💡 Best Practices ✔️ Use specific exception types ✔️ Avoid empty catch blocks ✔️ Don’t overuse checked exceptions ✔️ Always close resources using finally or try-with-resources. 🚀 In Short: Exception Handling = Writing safe, reliable, and crash-free Java code! #Java #ExceptionHandling #Coding #JavaInterview #LearnJava #SoftwareDevelopment #TechCareers #ProgrammingTips.
To view or add a comment, sign in
-
* Exception Handling in Java: In Java, Exception Handling helps us deal with unexpected events (errors) gracefully without crashing the program * What is an Exception? An exception is an event that disrupts the normal flow of execution. It can occur due to runtime errors like: Division by zero File not found Null reference access ⚙️ Key Keywords: 1)try → Block of code to test for errors. 2)catch → Handles the exception. 3)finally → Executes code whether exception occurs or not. 4)throw → Used to throw an exception manually. 5)throws → Declares exceptions in method signature. 🧩 Example: public class ExceptionExample { public static void main(String[] args) { try { int a = 10 / 0; // ArithmeticException } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); } finally { System.out.println("Execution complete!"); } } } ✅ Output: Cannot divide by zero! Execution complete! 📘 Types of Exceptions: 1️⃣ Checked Exceptions – Checked at compile time (e.g., IOException, SQLException). 2️⃣ Unchecked Exceptions – Occur at runtime (e.g., NullPointerException, ArithmeticException). 3️⃣ Errors – Serious issues (e.g., OutOfMemoryError) – not handled by application code. 💡 Best Practices ✔️ Use specific exception types ✔️ Avoid empty catch blocks ✔️ Don’t overuse checked exceptions ✔️ Always close resources using finally or try-with-resources. 🚀 In Short: Exception Handling = Writing safe, reliable, and crash-free Java code! #Java #ExceptionHandling #Coding #JavaInterview #LearnJava #SoftwareDevelopment #TechCareers #ProgrammingTips.
To view or add a comment, sign in
-
Java 2025: Smart, Stable, and Still the Future 💡 ☕ Day 4 — Structure of a Java Program Let’s break down how every Java program is structured 👇 🧩 Basic Structure Every Java program starts with a class — the main container holding variables, constructors, methods, and the main() method (the entry point of execution). Inside the class, logic is organized into static, non-static, and constructor sections — each with a specific role. 🏗️ Class — The Blueprint A class defines the structure and behavior of objects. It holds data (variables) and actions (methods). Execution always begins from the class containing the main() method. ⚙️ Constructor — The Initializer A constructor runs automatically when an object is created. It shares the class name, has no return type, and sets the initial state of the object. 🧠 Static vs Non-Static Static → Belongs to the class, runs once, shared by all objects. Non-static → Belongs to each object, runs separately. 🔹 Initializers Static block → Runs once when the class loads (for setup/configurations). Non-static block → Runs before the constructor every time an object is created. 🧩 Methods Static methods → Called without creating objects; used for utilities. Non-static methods → Accessed through objects; define object behavior. 🔄 Execution Flow 1️⃣ Class loads 2️⃣ Static block executes 3️⃣ main() runs 4️⃣ Non-static block executes 5️⃣ Constructor runs 6️⃣ Methods execute 💬 Class → Blueprint Constructor → Object initializer Methods → Define actions Static/Non-static → Class vs Object level Initializers → Run automatically before constructors Together, they create a structured, readable, and maintainable Java program. #Day4 #Java #JavaStructure #100DaysOfJava #OOPsConcepts #ConstructorInJava #StaticVsNonStatic #JavaForDevelopers #ProgrammingBasics #LearnJava #BackendDevelopment #CodeNewbie #DevCommunity
To view or add a comment, sign in
-
-
☕ 33 Core Technical Rules of Java 1. Everything in Java lives inside a class or interface. 2. One public class per file, and the file name must match it. 3. Main entry point: public static void main(String[] args). 4. Primitives (int, boolean, etc.) are not objects. 5. References hold addresses, not the actual values. 6. Strings are immutable and stored in the string pool. 7. Methods must always belong to a class or interface. 8. Constructors have no return type and share the class name. 9. this → current instance; super → parent class. 10. Static members belong to the class, not instances. 11. Overloading → compile-time; Overriding → runtime. 12. Every object extends java.lang.Object. 13. Garbage Collection is automatic — no manual freeing. 14. Access modifiers control visibility (public, private, etc.). 15. final means no modification (variable, method, class). 16. Interfaces can’t hold mutable state. 17. Abstract classes can’t be instantiated. 18. Generics are type-erased at runtime. 19. Arrays are covariant and know their length. 20. Exceptions are divided into checked and unchecked. 21. Checked exceptions must be declared with throws. 22. Threads must start via start(), not run(). 23. synchronized locks on the object monitor. 24. Enums are full classes with fields and methods. 25. Autoboxing handles primitive ↔ wrapper conversions. 26. Annotations can exist at source, class, or runtime. 27. Reflection gives runtime access to class metadata. 28. instanceof checks type; casting may throw exceptions. 29. Fields have default values; locals don’t. 30. Java is pass-by-value only (references are copied by value). 31. switch supports String, enum, and primitives. 32. Modules (module-info.java) define explicit dependencies. 33. The JVM verifies bytecode integrity before execution. #Java #ProgrammingLanguages #SoftwareEngineering #BackendDevelopment #CodeTips #Developers #SystemProgramming #TechPost
To view or add a comment, sign in
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development